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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序