Laravel 在多态表上按列对结果进行排序

Bra*_*rse 1 php mysql eloquent laravel-5

简短的问题

使用 Laravel 的 Eloquent 模型;如何按具有morphMany多态关系的列对查询进行排序?

较长的问题

假设我有给定的表结构:

// table: images
+ -- + ------------ + -------------- + ----- + ----------- +
| id | imageable_id | imageable_type | views | upload_date |
+ -- + ------------ + -------------- + ----- + ----------- +
| 1  | 1            | User           | 100   | 2016-16-06  |
| 2  | 3            | User           | 200   | 2016-16-06  |
+ -- + ------------ + -------------- + ----- + ----------- +

// table: users
+ -- + ---- +
| id | name |
+ -- + ---- +
| 1  | Bob  |
| 2  | Kat  |
+ -- + ---- +
Run Code Online (Sandbox Code Playgroud)

...我有一个User具有morphMany多态关系的 Eloquent 模型。

如何根据用户今天上传的图像收到的观看次数对用户进行排序?

我自己也尝试过这个问题,但未能找到解决方案。我最接近正确的顺序是当我使用与此类似的查询时:

User::with([
   'images' => function ($query) {
       $query->where('upload_date', Carbon::today()->toDateString())
           ->orderBy('views', 'DESC');
   }
])->get();
Run Code Online (Sandbox Code Playgroud)

但是,在尝试此操作后,我很明显,用户现在按其递增的 id 排序,而不是表views上的列,这是错误的images

预先感谢所有帮助我解决这个问题的人。

Bra*_*rse 6

我想通了,这要归功于这篇文章的评论http://laravel.io/forum/02-21-2014-order-and-paginate-a-collection-by-a-releted-field-using-eloquent

User::leftJoin('images', function ($join) {
    $join->on('users.id', '=', 'images.imageable_id')
        ->where('imageable_type', '=', 'User')
        ->where('upload_date', '=', Carbon::today()->toDateString());
})
    ->orderBy('images.views')
    ->select(['players.*']);
Run Code Online (Sandbox Code Playgroud)

我之前尝试过类似的操作,但遇到了问题,因为 id 和其他列在两个连接表之间发生冲突。区别就在这一次->select(['users.*'])。现在,仅返回用户的数据。