2017-08-28 91 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