按关系值对集合进行排序 [英] Sort collection by relationship value

查看:90
本文介绍了按关系值对集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按嵌套关系的属性对laravel集合进行排序.

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.

当前代码:

Project.php

Project.php

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

Task.php

public function project()
{
    return $this->belongsTo('App\Models\Project');
}

UserController

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!

推荐答案

我认为您需要使用

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

例如:

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()

更新

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

在查询中添加with为:

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

这篇关于按关系值对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆