duanbing6955 2017-04-23 21:37
浏览 28
已采纳

Laravel:使用数据透视表时在查询级别订购数据?

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.

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);
}

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)
         @include('posts.post')
      @endforeach

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);
    }
    

    to

    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) {
             $query->orderBy('tags.created_at','desc');
        }
    ])->get();
    

    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.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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 关于#用户注册#的问题,如何解决?