2017-08-03 174 views
0

我想從數據透視表中的列中對laravel中的雄辯查詢進行排序。Laravel按數據透視表列排序

基本上只要產品被用戶所青睞,它就會被添加到數據透視表中,並且它應該首先顯示收藏的,然後是剩餘的。因爲我將在刀片中使用foreach。

產品表中包含這些列:

id, category, product_name, priority, status, created_at, updated_at 

用戶表中包含這些列:

public function favorites() 
{ 
    return $this->belongsToMany(Products::class, 'favorites', 'user_id', 'product_id') 
       ->withTimeStamps(); 
} 

收藏表包含這些列:

id, name, email, created_at, updated_at 

在用戶模式下:

id, user_id, product_id, created_at, updated_at 

在控制器方面,雄辯的查詢是目前:

$productinprogress = Products::all() 
    ->sortByDesc("priority") 
    ->where('status', 'inprogress'); 

我只是困惑,如何解決這一點。

您的幫助表示讚賞。非常感謝。

回答

0

,你可以使用類似波紋管:

$productinprogress = Products::all() 
    ->where('status', 'inprogress') 
    ->sortByDesc("priority"); 

,如果你使用預先加載和加載收藏也需要一個有效的解決方案下面的代碼

$productinprogress = Products::all() 
    ->with('favorites') 
    ->where('status', 'inprogress') 
    ->sortByDesc("priority"); 
+0

BadMethodCallException 方法不存在。 – RSK

+0

我看不到數據庫中的任何優先級字段,您是否可以嘗試改變其中存在的任何其他字段的優先級 –

+0

它實際上可用,忘記放在頂部。所以優先領域是可用的。 – RSK

0

使用,我認爲你應該讓兩個查詢爲避免加載重複產品,第一個適用於喜歡的產品,第二個應該是這樣的一些東西:

Products::all()->sortByDesc("priority")->where('status', 'inprogress')->whereNotIn('id', $favorite_products); 

然後在刀片文件中,您創建了兩個foreach,第一個用於收藏,第二個用於其他。