Laravel 5.2 - select 帖子按标签和降序排列
Laravel 5.2 - select posts by tag and order descending
我在我的 Laravel 项目中堆叠了按标签选择的帖子,并按降序排列。我想按特定标签显示帖子。我创建了具有 manyToMany
关系的 Post
和 Tag
模型。我还使用 post_id
和 tag_id
创建了一个枢轴 table 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) 进行查询,但在 Posts table 中按 posts.created_at 字段排序?这是我的 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
table 中的 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'));
}
并在 blade 中:
@foreach($tag as $post)
{{ $post->title }}
@endforeach
我在我的 Laravel 项目中堆叠了按标签选择的帖子,并按降序排列。我想按特定标签显示帖子。我创建了具有 manyToMany
关系的 Post
和 Tag
模型。我还使用 post_id
和 tag_id
创建了一个枢轴 table 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) 进行查询,但在 Posts table 中按 posts.created_at 字段排序?这是我的 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
table 中的 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'));
}
并在 blade 中:
@foreach($tag as $post)
{{ $post->title }}
@endforeach