Laravel: OrderBy the paginated Eloquent relationship result

时间:2016-03-02 10:54:12

标签: php pagination laravel-5.2

My application uses Laravel 5.2

I have two models: Links and Affiliates. The relationship between them is: Link hasMany Affiliates. When I want the Affiliates for a Link, I'd like to paginate the result, which works as expected, but I also want to Order by the result. How do I do that?

This is how my current code is:

$affiliates = $link->affiliates->paginate(50, ['*'], 'p')->orderBy('created_at', 'desc')->orderBy('visitor_ip', 'desc');

Thanks!

1 个答案:

答案 0 :(得分:2)

Something like this should work:

$affiliates = Affiliate::where('link_id', $id)->orderBy('created_at', 'desc')->orderBy('visitor_ip', 'desc')->paginate(50, ['*'], 'p');