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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了