Laravel 5.2 -按标签和降序选择帖子


Laravel 5.2 - select posts by tag and order descending

我在我的Laravel项目中使用按降序排序的标签选择帖子。我想通过特定的标签显示帖子。我创建了具有manyToMany关系的PostTag模型。我还用post_idtag_id创建了一个数据透视表post_tag。在PostsController我创建tags()方法:

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)进行查询,但按帖子排序。created_at字段在Posts表?这是我的Post和Tag模型,有许多关系:

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()方法。请帮助。

我找到了解决方案,这里是答案

对于标签模型的降序,posts()方法应该是:

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

find()方法应该是这样的:

public function tags($tagid)
    {
        $tag = $this->tags->find($tagid)->posts()->paginate(12);
        return view('frontend.posts.tag', compact('tag'));
    }

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