Laravel在多态表上按列排序结果 [英] Laravel order results by column on polymorphic table
本文介绍了Laravel在多态表上按列排序结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简短问题
使用Laravel的口才模型;如何按具有 morphMany
多态关系的列排序查询?
更长的问题
说我有给定的表结构:
//表:图像+-+ ------------ + -------------- + ----- + ----------- +|id |imageable_id |imageable_type |意见|upload_date |+-+ ------------ + -------------- + ----- + ----------- +|1 |1 |用户|100 |2016-16-06 ||2 |3 |用户|200 |2016-16-06 |+-+ ------------ + -------------- + ----- + ----------- +//表格:用户+-+ ---- +|id |名称|+-+ ---- +|1 |鲍勃||2 |吉|+-+ ---- +
...并且我有一个雄辩的 User
模型,它具有 morphMany
多态关系.
如何根据用户今天上传的图片的观看次数来订购用户?
我本人已经尝试过此问题,但无法找到解决方案.我最接近正确排序的是当我使用与此类似的查询时:
User :: with(['图像'=>函数($ query){$ query-> where('upload_date',Carbon :: today()-> toDateString())-> orderBy('views','DESC');}])-> get();
但是,在尝试了这一点之后,对我来说,显而易见的是,用户现在通过其递增ID而不是 images
表上的 views
列错误地排序了./p>
在此感谢您在我的旅程中为我提供帮助的任何人.
解决方案
感谢这篇帖子的评论 解决方案
I figured it out thanks to a comment on this post 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.*']);
I tried something similar to this before but was encountering problems because the ids, and other columns, were clashing between the two joined tables. The difference this time being ->select(['users.*'])
. Now, only the user's data is returned.
这篇关于Laravel在多态表上按列排序结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文