我正在尝试使用Laravel和eloquent根据以下查询返回结果。
$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->orderBy('created_at', 'desc')
->paginate(5);
好的,这很好,它返回它应该返回的,所有与其他表有关联关系的博客文章。
我现在想做的是只返回$blogPosts,其中一个标签被用户单击。假设有一个标签"PHP",那么我把这个值作为$tag传递给方法。然后我有这样的东西
public function tag_search($tag)
{
$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->where('tags', $tag)
->orderBy('created_at', 'desc')
->paginate(5);
$categories = BlogCategories::with('blog_posts')->get();
$data = array('blogPosts' => $blogPosts, 'categories' => $categories,
);
return view('blog.index')->with($data);
}
现在我的问题实际上是相对简单的我猜,如果where子句是一个列在BlogPosts表它会工作,我知道这是因为我尝试过。
然而,上面的内容不能正常工作,我只能使用;
->where('x', y)
其中x是BlogPosts
表中的一个字段。我想返回一组值,其中提交的$标签与附加到博客文章的标签相关联的值相同。
有意义吗?我想我想太多了,我只是现在没有想
添加列字段'tags'到您的表,然后这些查询:
$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->where('tags', '=', $tag)
->orderBy('created_at', 'desc')
->paginate(5);
$categories = BlogCategories::with('blog_posts')->get();
return view('blog.index', compact ('categories', 'blogposts'));
好的,所以答案是像这样使用where。
$blogPosts = BlogPosts::whereHas('tags', function ($query) use ($tag) {
$query->where('name', $tag);
})->orderBy('created_at', 'desc')
->paginate(5);
返回基于关联元素的搜索。