laravel 按关系值对集合进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41189785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort collection by relationship value
提问by frederikvdbe
I want to sort a laravel collection by an attribute of an nested relationship.
我想通过嵌套关系的属性对 laravel 集合进行排序。
So I query all projects (only where the project has tasks related to the current user), and then I want to sort the projects by deadline date of the task relationship.
所以我查询了所有的项目(只在项目有与当前用户相关的任务的地方),然后我想按照任务关系的截止日期对项目进行排序。
Current code:
当前代码:
Project.php
项目.php
public function tasks()
{
return $this->hasMany('App\Models\ProjectTask');
}
Task.php
任务.php
public function project()
{
return $this->belongsTo('App\Models\Project');
}
UserController
用户控制器
$projects = Project->whereHas('tasks', function($query){
$query->where('user_id', Auth::user()->id);
})->get()->sortBy(function($project){
return $project->tasks()->orderby('deadline')->first();
});
I don't know if im even in the right direction? Any advice is appreciated!
我不知道我是否在正确的方向上?任何建议表示赞赏!
采纳答案by Amit Gupta
I think you need to use something like join()
and then sort by whatever you need.
我认为你需要使用类似的东西join()
,然后按你需要的任何东西排序。
For exapmle:
例如:
Project::join('tasks', 'tasks.project_id', '=', 'projects.id')
->select('projects.*', DB::raw("MAX(tasks.deadline) as deadline_date"))
->groupBy('tasks.project_id')
->orderBy('deadline_date')
->get()
Update
更新
Project::join('tasks', function ($join) {
$join->on('tasks.project_id', '=', 'projects.id')
->where('tasks.user_id', Auth::user()->id)
->whereNull('tasks.completed');
})
->select('projects.*', DB::raw("MAX(tasks.deadline) as deadline_date"))
->groupBy('tasks.project_id')
->orderBy('deadline_date')
->get()
Update2
更新2
Add with
in your query as:
将with
您的查询添加为:
->with(['tasks' => function ($q) {
$q->where('user_id', Auth::user()->id)
->whereNull('completed');
})
回答by Spholt
A nice clean way of doing this is with the .
operator
一个很好的干净的方法是与.
操作员
$projects = Project::all()->load('tasks')->sortBy('tasks.deadline');
回答by Roshan Perera
Try This,
尝试这个,
$tasks = Task::with('project')
->where('user_id',Auth::user()->id)
->orderBy('deadline')
->get();
After that you can access project properties like below
之后,您可以访问如下所示的项目属性
$tasks->first()->project()->xxx