laravel 如何使用 Builder“按...排序”一个 Eloquent 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17475299/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:05:24  来源:igfitidea点击:

How to "order by ..." an Eloquent relationship using Builder

laravellaravel-4relationshipeloquent

提问by Eduardo Kasper

I have to order a query, from a relationship in Laravel 4. There are two Models: Taskand Subproject.

我必须从 Laravel 4 中的关系中订购一个查询。有两个模型:TaskSubproject

In TaskI have a relationship with Subproject. This way:

Task我与Subproject. 这边走:

public function subproject() 
{
    return $this->belongsTo('Subproject');
}

From my Controller, I want to order Subprojectusing Laravel Builderand not joins.

从我的Controller,我想订购Subproject使用Laravel Builder而不是加入。

Is there a way to do it?

有没有办法做到这一点?

采纳答案by Alexandre Butynski

What you want to do is is eager loading. Load a model and it's linked model in a single request. You can do this with the Eloquent::with()method, like that :

您要做的是预先加载。在单个请求中加载模型及其链接模型。您可以使用该Eloquent::with()方法执行此操作,如下所示:

$subprojects = Subproject::with('task')->orderBy('subproject.id')->get();

Then you get a list of subprojects with, in memory, the linked tasks and you can call tasks without anymore SQL request :

然后你会得到一个子项目列表,在内存中,链接的任务,你可以在没有 SQL 请求的情况下调用任务:

foreach($subprojects as $project) {
    echo $project->task->id;
}

回答by The Alpha

From the comment :

从评论:

I want to order based on a parent table. Like that: select subprojects.id, tasks.id from tasks join subprojects on tasks.subproject_id = subprojects.id order by subprojects.id

我想根据父表订购。像这样:选择subprojects.id,tasks.id从tasks join subprojects on tasks.subproject_id = subprojects.id order by subprojects.id

It could be achived using following :

可以使用以下方法实现:

DB::table('tasks')
->join('subprojects', 'tasks.subproject_id', '=', 'subprojects.id')
->order_by('subprojects.id', 'ASC') // DESC
->select('subprojects.id,', 'tasks.id')
->get(); // for pagination you can use: ->paginate(5)