laravel Eloquent whereHas 上的 OrderBy

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

OrderBy on Eloquent whereHas relationship

laraveleloquentlaravel-eloquent

提问by benmacgowan

I have a simple page which lists counties and there related items under headings. These items need to be approved, hence the whereHas method.

我有一个简单的页面,其中列出了县和标题下的相关项目。这些项目必须是approved,因此是 whereHas 方法。

I currently have the following eloquent query;

我目前有以下雄辩的查询;

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1);
})->get();

The itemsreturned are currently ordered by their primary field id(it would seem), however I want to list these items alphabetically by their namefield.

items返回目前由他们的主要字段排序id(这似乎),但我想通过自己的字母顺序列出这些项目name领域。

I have tried the following query, but this does change anything. Any advice would be appreciated?

我尝试了以下查询,但这确实改变了任何事情。任何意见,将不胜感激?

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1)->orderBy('name');
})->get();

采纳答案by Mathieu Ferre

when you want to display the result , try this :

当你想显示结果时,试试这个:

@foreach($counties as $county)
    @foreach($county->items->orderBy('name') as $item)
          {{ $item->name }}
    @endforeach
@endforeach

Or in your County Models :

或在您的县模型中:

public function approvedItems(){
    return $this->hasMany(Item::class)->where('approved', 1)->orderBy('name');
}

and then :

进而 :

controller :

控制器 :

$counties = County::whereHas('approvedItems')->get();

view :

看法 :

@foreach($counties as $county)
    @foreach($county->approvedItems as $item)
          {{ $item->name }}
    @endforeach
@endforeach

Try to work with your models and relationships for having the lightest controller you can, you will gain in lisibility

尝试使用您的模型和关系以获得最轻的控制器,您将获得可理解性

回答by Sérgio Reis

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1);
})->orderBy('name')->get();

I don't think you can order on the subquery, it should be before the ->get

我认为您不能对子查询进行排序,它应该在 ->get 之前

回答by James Bailey

To keep it eloquent, you can put it in the relation, in the Model class:

为了保持流畅,您可以将其放在 Model 类中的关系中:

public function reviews()
{
    return $this->hasMany(Review::class)->orderBy('id','desc');
}

https://laravel.io/forum/09-14-2015-ordering-a-collection-by-the-related-items

https://laravel.io/forum/09-14-2015-ordering-a-collection-by-the-related-items

Might be late, but hopefully someone stumbles on this (it's the first in google search)

可能会迟到,但希望有人偶然发现(这是谷歌搜索中的第一个)

回答by John

$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');