php Laravel Eloquent:如何对相关模型的结果进行排序?

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

Laravel Eloquent: How to order results of related models?

phplaravellaravel-4eloquent

提问by Debiprasad

I have a model called Schooland it has many Students.

我有一个名为School的模型,它有很多学生

Here is the code in my model:

这是我模型中的代码:

public function students()
{
    return $this->hasMany('Student');
}

I am getting all the students with this code in my controller:

我让所有学生都在我的控制器中使用此代码:

$school = School::find($schoolId);

and in the view:

并在视图中:

@foreach ($school->students as $student)

Now I want to order the Studentsby some field in the studentstable. How can I do that?

现在我想按表中的某个字段对学生进行排序students。我怎样才能做到这一点?

回答by Jarek Tkaczyk

You have a few ways of achieving this:

您有几种方法可以实现这一点:

// when eager loading
$school = School::with(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}])->find($schoolId);

// when lazy loading
$school = School::find($schoolId);
$school->load(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}]);

// or on the collection
$school = School::find($schoolId);
// asc
$school->students->sortBy('whateverProperty');
// desc
$school->students->sortByDesc('whateverProperty');


// or querying students directly
$students = Student::whereHas('school', function ($q) use ($schoolId) {
  $q->where('id', $schoolId);
})->orderBy('whateverField')->get();

回答by fico7489

you can add orderBy to your relation, so the only thing you need to change is

您可以将 orderBy 添加到您的关系中,因此您唯一需要更改的是

public function students()
{
    return $this->hasMany('Student');
}

to

public function students()
{
    return $this->hasMany('Student')->orderBy('id', 'desc');
}

回答by Jason

To answer the original question, the studentsdynamic property can also be accessed as a relationship method.

为了回答最初的问题,students动态属性也可以作为一种关系方法来访问。

So you have this to fetch all students:

所以你有这个来获取所有学生:

$students = $school->students;

Now as a relationship method, this is equivalent:

现在作为一种关系方法,这是等效的:

$students = $school->students()->get();

Given this, you can now add in some ordering:

鉴于此,您现在可以添加一些排序:

$students = $school->students()->orderBy('students.last_name')->get();

Since eloquent will be performing a join, make sure to include the table name when referencing the column to order by.

由于 eloquent 将执行连接,因此在引用要排序的列时确保包含表名。

You can also add this to your studentsmethod if you want to set a default order that $school->studentswill always return. Check out the documentation for hasMany()to see how this works.

students如果您想设置一个$school->students总是返回的默认顺序,您也可以将它添加到您的方法中。查看文档hasMany()以了解其工作原理。

回答by Madhavi Khatal

For Many to one relation I found one answer on:

对于多对一的关系,我找到了一个答案:

https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship

https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship

$order = 'desc';
$users = User::join('roles', 'users.role_id', '=', 'roles.id')
  ->orderBy('roles.label', $order)
  ->select('users.*')
  ->paginate(10);

this can save day... of anyone

这可以挽救任何人的一天......

回答by FaridLU

You can use this like this:

你可以这样使用它:

$students = $school->students()->orderBy('id', 'desc');

You can also use

你也可以使用

$students = $school->students()->orderBy('id', 'desc')->paginate(10);