2017-08-28 132 views
1

我在模型OrderProduct簡單belongsToMany關係:Laravel關係排序依據

public function statuses() 
{ 
    return $this->belongsToMany(OrderProductStatusName::class, 'order_product_statuses') 
     ->withPivot('created_at'); 
} 

我想有一個產品的所有狀態,但我希望他們通過排序依據透視表上created_at。 我試圖這樣做:

$orderProduct = OrderProduct::find($productId); 

$statuses = $orderProduct->statuses->orderBy('pivot_created_at', 'DESC'); 

但我有一個方法OrderBy不存在錯誤500。我怎樣才能做到這一點?

+0

'statuses'將是一個集合,它使用'sort'和'sortBy'代替雄辯的'orderBy' – aynber

+0

我tryed如你所說,但仍然錯誤500 ( $ status = $ orderProduct-> statuses-> sortBy('pivot_created_at','DESC'); – wenus

+0

嘗試'sortByDesc'而不是每當你得到一個錯誤500,總是看錯誤日誌找出原因。 – aynber

回答

2

laravel中的關係可以用作屬性或方法。如果關係用作屬性,則返回一個集合。如果用作方法,則返回查詢生成器對象,並且可以鏈接orderBy之類的方法。因此,在這種情況下,你應該使用下面的代碼:

$statuses = $orderProduct->statuses()->orderBy('pivot_created_at', 'DESC')->get(); 
+0

感謝您提供非常有用的提示!! :) – wenus