2016-09-06 30 views
0

我堆放在我的Laravel項目中,帖子通過標籤選擇,按降序排序。我想通過特定標籤顯示帖子。我使用manyToMany關係創建了PostTag模型。我還創建了一個數據透視表post_tagpost_idtag_id。在PostsController創建tags()方法:Laravel 5.2 - 按標籤和順序選擇帖子降

public function tags($tagid) 
    { 
     $tag = $this->tags->find($tagid); 

     return view('frontend.posts.tag', compact('tag')); 
    } 

和循環它的觀點:

@foreach($tag->posts as $post) 
    {{ $post->title }} 
    .... 
@endforeach 

這對我的作品,但我需要按posts.created_at帖子降序排列。如何使用Tag :: find($ id)進行查詢,但通過Posts表中的posts.created_at字段進行排序?這是我的郵政和標籤型號多對多關係:

class Post extends Model 
{ 
    ..... 

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

class Tag extends Model 
{ 
    protected $fillable = ['name']; 

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

請,如何訂購在表posts通過created_at列降序排列由特定的標籤選中的帖子?我也希望按降序使用該查詢中的paginate()metohd。請幫忙。

回答

0

我找到解決辦法,這裏是回答

對於標籤模型的帖子降序排列()方法應該是:

public function posts() 
    { 
     return $this->belongsToMany(Post::class)->orderBy('created_at', 'desc'); 
    } 

find()方法中TagController方法應該是這樣的:

public function tags($tagid) 
    { 
     $tag = $this->tags->find($tagid)->posts()->paginate(12); 

     return view('frontend.posts.tag', compact('tag')); 
    } 

and in blade:

@foreach($tag as $post) 
    {{ $post->title }} 
@endforeach