gpt4 book ai didi

php - Laravel 按多态表上的列排序结果

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:23 25 4
gpt4 key购买 nike

小问题

使用 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 |
+ -- + ---- +

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

我如何根据用户今天上传的图片获得的浏览量对用户进行排序?

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

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

但是,在尝试这个之后,我很明显地发现用户现在按他们递增的 ID 错误排序,而不是 images 表上的 views 列。

提前感谢在我解决这个问题的过程中帮助我的任何人。

最佳答案

感谢这篇文章的评论,我明白了 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.*']);

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

关于php - Laravel 按多态表上的列排序结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37852995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com