Laravel:使用数据透视表时在查询级别对数据进行排序?

Laravel: Ordering data at a query level when using pivot tables?

在我的 routes/web.php 中,我有一条这样的路线...

Route::get('/tags/{tag}', 'TagsController@show');

然后,在 TagsController 内部,因为我有一个 post_tag 枢轴 table 已被定义为多对多关系。

Tag.php...

public function posts(){
    return $this->belongsToMany(Post::class);
}

public function getRouteKeyName(){
  return 'name';
}

Post.php...

public function tags(){
    return $this->belongsToMany(Tag::class);
}

我得到了这样一个特定标签的帖子...

public function show(Tag $tag){
    $posts = $tag->posts;
    return view('posts.index', compact('posts','tag'));
}

然后,要先将帖子排序为最新的,我可以在 index.blade.php...

中执行此操作
      @foreach ($posts->sortByDesc('created_at') as $post)
         @include('posts.post')
      @endforeach

这很好用,但是当我更喜欢在查询级别进行重新排序时,我正在集合级别进行重新排序。

Eloquent: Relationships 我可以看到我可以做这样的事情,这也有效...

$user = App\User::find(1);
foreach ($user->roles as $role) {
    //
}

但是,这样的事情似乎行不通...

public function show($tag){
    $posts = \App\Tag::find($tag);
    return view('posts.index', compact('posts'));
}

我的问题是,如何在使用数据透视表 tables 时 filter/order 查询级别的数据?

要订购您的 collection,您必须更改

public function tags(){
    return $this->belongsToMany(Tag::class);
}

public function tags(){
    return $this->belongsToMany(Tag::class)->orderBy('created_at');
}

扩展@leli。 1337 个回答

在不更改创建的关系的情况下订购内容。

首先,保持原来的关系

class User 
{ 
    public function tags
    {
       return $this->belongsToMany(Tag::class);
    }
}

其次,在构建查询期间执行以下操作

//say you are doing query building

$users = User::with([
    'tags' => function($query) {
         $query->orderBy('tags.created_at','desc');
    }
])->get();

有了这个,您可以对标签数据的内容进行排序,如果需要,您还可以在查询级别向标签添加更多 where 子句 table 查询构建器。