我通过 post_tags
对 post
和 tags
使用 Eloquent 关系。我想做的是在我的前端 View 中使用特定的标签
制作posts
的部分。就像如果我有一个 1
部分,它应该包含标签 "new"
的所有帖子,2
部分应该包含标签 的所有帖子“旧”
等。我希望所有这些都发生在同一个 View 中。
发布模型
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag');
}
标签模型
public function posts()
{
return $this->belongsToMany('App\Post', 'post_tag');
}
Controller
public function index()
{
$posts = Post::all();
return view('frontend.index')->withPosts($posts);
}
请帮帮我:)
最佳答案
您可以通过加载帖子来获取所有标签:
public function index()
{
$tags = Tag::with('posts')->get();
return view('frontend.index')->withTags($tags);
}
在 View 中你可以做这样的事情:
@foreach ($tags as $tag)
<h2>Tag : {{ $tag->name }}</h2>
@foreach ($tag->posts as $post)
<p>Post : {{ $post->title }}</p>
@endforeach
@endforeach
获取带有标签的帖子:
public function index()
{
$tagName = 'new';
$posts = Post::whereHas('tags', function ($q) use($tagName) {
$q->where('name', $tagName);
})->get();
return view('frontend.index')->withTagName($tagName)->withPosts($posts);
}
在 View 中您可以执行以下操作:
<h2>Tag : {{ $tagName }}</h2>
@foreach ($posts as $post)
<p>Post : {{ $post->title }}</p>
@endforeach
如果你想从 View 中进行查询,你可以这样做(但这不是一个好的做法,因为 View 只是用于查看内容而不是从数据库获取内容):
<?php foreach ((\App\Post::whereHas('tags', function ($q) use($tagName) {
$q->where('name', $tagName);
})->get()) as $post) { ?>
<p>Post : {{ $post->title }}</p>
<?php } ?>
关于php - 获取laravel中带有特定标签的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883100/