wenus
wenus

Reputation: 1505

Laravel relationships orderBy

I have a simple belongsToMany relationship in model OrderProduct:

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

I want to have all statuses for one product, but I want them to orderBy by pivot table on created_at. I was trying to do like this:

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

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

But i have error 500 that method orderBy doesn't exist. How can I do this?

Upvotes: 1

Views: 221

Answers (1)

Alireza Hoseinzadeh
Alireza Hoseinzadeh

Reputation: 606

Relations in laravel can be used as property or method. If relations used as property then returns a collection. if used as methods then returns query builder object and you can chain methods like orderBy. So in this case you should use the below code :

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

Upvotes: 2

Related Questions