How to order by using appended attribute in Laravel

后端 未结 5 1039
南旧
南旧 2021-02-13 19:05

I created an appends attribute in Laravel Model, from the code below.

    protected $appends = array(\'total\'=>\'\');

And I set the returne

5条回答
  •  不知归路
    2021-02-13 19:58

    As mentioned, the proposed solution using a sortBy() callback does not work with paging.
    Here is an alternative to the accepted solution:

    orderByRaw()

    If the appended attributes can be calculated from the fields in your query you can instead use orderByRaw(), like so:

    // For example, booking percentage
    $query->orderByRaw('bookings_count / total_count');
    

    Check out a more advanced example here: laravel orderByRaw() on the query builder

提交回复
热议问题