Eloquent whereHas 关系上的 OrderBy

ben*_*wan 7 laravel eloquent

我有一个简单的页面,其中列出了县以及标题下的相关项目。这些项目需要是approved,因此需要使用 whereHas 方法。

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

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

返回items的内容当前按其主要字段排序id(看起来),但是我想按其name字段的字母顺序列出这些项目。

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

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

Mat*_*rre 0

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

@foreach($counties as $county)
    @foreach($county->items->orderBy('name') as $item)
          {{ $item->name }}
    @endforeach
@endforeach
Run Code Online (Sandbox Code Playgroud)

或者在您的县模型中:

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

进而 :

控制器 :

$counties = County::whereHas('approvedItems')->get();
Run Code Online (Sandbox Code Playgroud)

看法 :

@foreach($counties as $county)
    @foreach($county->approvedItems as $item)
          {{ $item->name }}
    @endforeach
@endforeach
Run Code Online (Sandbox Code Playgroud)

尝试与您的模型和关系合作,以获得尽可能轻的控制器,您将获得灵活性