問題描述
在我的數(shù)據(jù)庫中,我有:
In my Database, I have:
tops
表格posts
表格tops_has_posts
表格.
tops
Tableposts
Tabletops_has_posts
Table.
當(dāng)我在 tops
表中檢索頂部時,我還會檢索與頂部相關(guān)的 posts
.但是如果我想按特定順序檢索這些帖子怎么辦?所以我在我的數(shù)據(jù)透視表 tops_has_posts
中添加了一個 range
字段,我嘗試使用 Eloquent 按結(jié)果排序,但它不起作用.
When I retrieve a top on my tops
table I also retrieve the posts
in relation with the top.
But what if I want to retrieve these posts in a certain order ?
So I add a range
field in my pivot table tops_has_posts
and I my trying to order by the result using Eloquent but it doesn't work.
我試試這個:
$top->articles()->whereHas('articles', function($q) {
$q->orderBy('range', 'ASC');
})->get()->toArray();
還有這個:
$top->articles()->orderBy('range', 'ASC')->get()->toArray();
兩者都是絕望的嘗試.
提前致謝.
推薦答案
有兩種方法 - 一種是指定 table.field
,另一種使用 Eloquent 別名 pivot_field
if你使用 withPivot('field')
:
There are 2 ways - one with specifying the table.field
, other using Eloquent alias pivot_field
if you use withPivot('field')
:
// if you use withPivot
public function articles()
{
return $this->belongsToMany('Article', 'tops_has_posts')->withPivot('range');
}
// then: (with not whereHas)
$top = Top::with(['articles' => function ($q) {
$q->orderBy('pivot_range', 'asc');
}])->first(); // or get() or whatever
這會起作用,因為 Eloquent 將 withPivot
中提供的所有字段別名為 pivot_field_name
.
This will work, because Eloquent aliases all fields provided in withPivot
as pivot_field_name
.
現(xiàn)在,通用解決方案:
$top = Top::with(['articles' => function ($q) {
$q->orderBy('tops_has_posts.range', 'asc');
}])->first(); // or get() or whatever
// or:
$top = Top::first();
$articles = $top->articles()->orderBy('tops_has_posts.range', 'asc')->get();
這將對相關(guān)查詢進行排序.
This will order the related query.
注意:不要因為這樣命名事情而使您的生活變得艱難.posts
不一定是 articles
,我會使用一個或另一個名稱,除非確實需要這樣做.
Note: Don't make your life hard with naming things this way. posts
are not necessarily articles
, I would use either one or the other name, unless there is really need for this.
這篇關(guān)于如何在 Laravel 的 Eloquent ORM 中按數(shù)據(jù)透視表數(shù)據(jù)排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!