duanbing6955 2017-04-23 21:37
浏览 28


In my routes/web.php I have a route like this...

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

Then, inside TagsController because I have a post_tag pivot table that has been defined as a many-to-many relationship.


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

public function getRouteKeyName(){
  return 'name';


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

I get the posts for a certain tag like this...

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

Then, to sort the posts into newest first I can do this in index.blade.php...

      @foreach ($posts->sortByDesc('created_at') as $post)

This works fine, but I'm doing the re-ordering at collection level when I'd prefer to do it at query level.

From Eloquent: Relationships I can see that I can do something like this, which also works...

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

But, something like this does not seem to work...

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

My question is, how can I filter/order the data at a query level when using pivot tables?

  • 写回答

2条回答 默认 最新

  • dongqiaolong9034 2017-04-23 21:51

    To order your collection you must change

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


    public function tags(){
        return $this->belongsToMany(Tag::class)->orderBy('created_at');
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
  • duaj39673 2017-04-24 11:51

    Extending @leli. 1337 answer

    To order content without changing the relation created.

    First, keep the original relation

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

    Second, during query building do the following

    //say you are doing query building
    $users = User::with([
        'tags' => function($query) {

    With this, you can order the content of tags data and in query level also if needed you can add more where clauses to the tags table query builder.




  • ¥20 python 3des pyDes库
  • ¥15 关于#mysql#安装失败的问题。MySQL
  • ¥15 想问一下for循环计算表达式的方法,第一次接触
  • ¥15 如何在VA框架上面加功能,去读取框架内任何app数据功能
  • ¥15 关于#c语言#的问题:用c或c++写一个计算下列问题有关软件工程的代码并加上分析
  • ¥15 Zeppelin0.10.0版本升级lib包下的shiro-web
  • ¥15 链表入队的指针内存问题
  • ¥20 vba如何写本地html文件执行js
  • ¥15 VS2022的C#如何创建
  • ¥20 关于#用户注册#的问题,如何解决?