按关系分组并按关系字段排序

时间:2019-10-30 18:46:24

标签: php laravel eloquent laravel-6 eloquent--relationship

我有些模型需要按特定顺序列出。我有许多Task都属于ProjectProject可以有多个Task,而几个Task可以属于许多Project

在我的TaskController@index中,我想列出所有Task,并按Project.idProject.updated_at分组。示例:

Project 1
- Task 1
- Task 2
- Task 3

Project 2
- Task 1
- Task 2
- Task 3

如何在TaskController中以最简单的方式解决此问题?

1 个答案:

答案 0 :(得分:1)

问题的关键是使用查询功能扩展关系$this->hasMany('Task')->orderBy('updated_at');

示例:

您的Project.php型号:

<?php

class Project
{
    public function tasks()
    {
        return $this->hasMany('Task')->orderBy('updated_at');
    }
}

您的TaskController.php控制器:

<?php

class TaskController
{
    public function index()
    {
        $projects = Project::with('tasks')->orderBy('updated_at')->get();

        // Then use $projects in the blade template
        return view('my-projects', compact('projects'));
    }
}

您的projects.blade.php刀片文件:

@foreach($projects as $project)

<p>{{$project->name}}</p>

<ul>
    @foreach($project->tasks as $task)
    <li>{{$task->name}}</li>
    @endforeach
</ul>

@endforeach