Sort collection by relationship value

南楼画角 提交于 2019-12-04 03:28:33

问题


I want to sort a laravel collection by an attribute of an nested relationship.

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

public function tasks()
{
    return $this->hasMany('App\Models\ProjectTask');
}

Task.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!


回答1:


I think you need to use something like join() and then sort by whatever you need.

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

Add with in your query as:

->with(['tasks' => function ($q) {
    $q->where('user_id', Auth::user()->id)
       ->whereNull('completed');
})



回答2:


A nice clean way of doing this is with the . operator

$projects = Project::all()->load('tasks')->sortBy('tasks.deadline');



回答3:


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


来源:https://stackoverflow.com/questions/41189785/sort-collection-by-relationship-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!