php - Laravel - 嵌套关系,按最近的嵌套排序父模型
问题描述
很难理解如何通过嵌套关系对我的 Laravel 模型进行排序。
这里是模型。
用户.php
// 通过数据透视表有许多 small_groups
public function small_groups()
{
return $this->belongsToMany('App\Models\SmallGroup')->withPivot('type')->withTimestamps();
}
SmallGroup.php
// 有很多 SmallGroupLessons
public function small_group_lessons()
{
return $this->hasMany('App\Models\SmallGroupLesson');
}
SmallGroupLessons.php
// 有很多 SmallGroupLessonComments
public function small_group_lesson_comments()
{
return $this->hasMany('App\Models\SmallGroupLessonComment');
}
SmallGroupLessonsComment.php
// 属于 SmallGroupLesson
public function small_group_lesson()
{
return $this->belongsTo('App\Models\SmallGroupLesson');
}
我正在尝试做的是拉出所有用户的小组,如果存在,则按最新的SmallGroupLessonComment 排序。我一直在做一些研究,听起来在这个用例中使用 Laravels ORM 是行不通的。但是,我不完全确定如何在嵌套关系上创建连接。
我尝试了以下方法,但这只会引入最新的 SmallGroupLessonComment,但是它不会对整个结果集进行排序。
$small_groups = $user->small_groups()->with([
'small_group_lessons' => function($q) {
$q->with([
'latest_comment' => function($q) {
$q->orderBy('created_at', 'asc');
}
]);
}
])->paginate($limit);
更新
能够通过以下方式解决它...
$small_groups = $user->small_groups()->with([
'small_group_lessons' => function($q) {
$q->with([
'latest_comment' => function($q) {
$q->orderBy('created_at', 'asc');
}
]);
}
])
->leftJoin('small_group_lessons', 'small_group_lessons.small_group_id', '=', 'small_groups.id')
->leftJoin('small_group_lesson_comments', 'small_group_lesson_comments.small_group_lesson_id', '=', 'small_group_lessons.id')
->orderBy('small_group_lesson_comments.created_at', 'desc')
->paginate($limit);
更新#2
以上不起作用。我得到了多个相同项目的小组。
更新#3
这个查询非常接近,但它只是由最近的 SmallGroupLesson 排序的。理想情况下,我们按 SmallGroupLessonComment 订购
$small_groups = $user->small_groups()->with(
[
'small_group_lessons' => function($q) {
$q->with('latest_comment');
$q->orderBy('created_at', 'desc');
}
],
)
->orderBy(
SmallGroupLesson::select('created_at')
->whereColumn('small_group_id', 'small_groups.id')
->orderBy(SmallGroupLessonComment::select('created_at')
->whereColumn('small_group_lesson_id', 'small_group_lessons.id')
->orderBy('created_at', 'desc')
->limit(1), 'desc')
->limit(1), 'desc'
)
->paginate();
解决方案
$data=User::select('*')->leftJoin('small_group_lessons','small_group_lessons.user_id','user.id') ->ordeBy('small_group_lessons.created_at','DESC')->get( );
试试这样
推荐阅读
- ios - 如何从 Widget 中的 ForEach 获取随机核心数据元素
- java - 如何在 Springboot 中使用 javax.ejb.TimerService
- reactjs - 反应受控与不受控制的输入形式
- sql - 查询返回空记录
- javascript - 为什么我从 React lib useSpring 中获取空返回值?
- google-sheets - 在 Google Sheets 'IF' 公式中使用多个 'OR' 语句,并带有 #ERROR 的连续范围
- css - 为什么文本容器和父容器一样长,而不是内部文本?
- sql - 我想在 SQL 中选择或查看特定数据
- python-3.x - 如何填充已识别的轮廓?
- javascript - 如何正确地将 JS 日期发送到 EF Core5 并返回?