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?

图片转代码服务由CSDN问答提供 功能建议

在我的 routes / web.php </ code>中我有这样的路线... < / p>

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

然后,在 TagsController </ code>中,因为我有一个 post_tag </ code>数据透视表,它被定义为多对多关系。 </ p>

Tag.php ... </ p>

  public function posts(){
 return $ this-&gt; belongsToMany(Post ::  class); 
} 
 
公共函数getRouteKeyName(){
 return'name'; 
} 
 </ code> </ pre> 
 
 

Post.php ... </ p>

  public function tags(){
 return $ this-&gt; belongsToMany(Tag :: class); 
} 
 </ code> </ pre> 
 \  n 

我收到了像这样的特定标签的帖子...... </ p>

  public function show(Tag $ tag){
 $ posts = $ tag-&gt; 帖子; 
返回视图('posts.index',compact('posts','tag')); 
} 
 </ code> </ pre> 
 
 

然后,排序 最新的帖子我可以在 index.blade.php </ code> ... </ p>

  @foreach($ posts-&gt; sortByDesc('created_at)中执行此操作 ')作为$ post)
 @include('posts.post')
 @endforeach 
 </ code> </ pre> 
 
 

这很好用,但我正在做的 我希望在查询级别进行收集时订购。</ p>

来自雄辩:Re lationships 我可以看到我可以做这样的事情,这也有效... </ p>

  $ user = App \ User :: find(1); \  nforeach($ user-&gt; role as $ role){
 // 
} 
 </ code> </ pre> 
 
 

但是,这样的东西似乎不起作用...... </ p>

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

我的问题是,如何在使用数据透视表时在查询级别过滤/排序数据?< / p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题