我在模型OrderProduct中有一个简单的belongsToMany关系:
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');
但我有错误500,方法orderBy不存在。我怎样才能做到这一点?
答案 0 :(得分:2)
laravel中的关系可以用作属性或方法。如果将关系用作属性,则返回集合。如果用作方法然后返回查询构建器对象,您可以链接orderBy之类的方法。所以在这种情况下你应该使用下面的代码:
$statuses = $orderProduct->statuses()->orderBy('pivot_created_at', 'DESC')->get();