Laravel 具有特定标签且具有特定标签的帖子除外
Laravel Posts that have specific tags and except have specific tags
我有 2 个模型 => post 和 tag(多对多关系),标签也有 2 种类型像“趋势”和“限制”
标签模型 table : id - tag_type - tag_title - tag_slug
public function getTags()
{
return $this->belongsToMany(Tag::class, 'tags_posts', 'post_id', 'tag_id');
}
我需要得到 posts :当 $request->trending 存在时 return posts 有 tag_type == "trending" 和 tag_title == $request->trending Also(这不是有条件的并且总是检查)除了 posts 有tag_type == "restrict" 和 tag_slug == "simple2"
我需要 eloquent laravel 而不是 php 数据库,优化很重要
感谢百万
扩展 lagbox 的评论,您正在寻找 whereHas 和 whereDoesntHave,将闭包传递给每个闭包以进行过滤:
Post::whereHas('tags', function($q) use($request){
if ($request->trending) {
$q->where('tag_type', $request->trending);
}
})
->whereDoesntHave('tags', function($q){
$q->where([
'tag_type' => 'restrict',
'tag_slug' => 'simple2'
]);
});
WhereHas 将 select 仅包含带有 tag_type === $request->trending 标签的帖子,
WhereDoesntHave 将过滤掉标签为 tag_type === 'restricted' 和 tag_slug === 'simple2'.
的帖子
我有 2 个模型 => post 和 tag(多对多关系),标签也有 2 种类型像“趋势”和“限制”
标签模型 table : id - tag_type - tag_title - tag_slug
public function getTags()
{
return $this->belongsToMany(Tag::class, 'tags_posts', 'post_id', 'tag_id');
}
我需要得到 posts :当 $request->trending 存在时 return posts 有 tag_type == "trending" 和 tag_title == $request->trending Also(这不是有条件的并且总是检查)除了 posts 有tag_type == "restrict" 和 tag_slug == "simple2"
我需要 eloquent laravel 而不是 php 数据库,优化很重要
感谢百万
扩展 lagbox 的评论,您正在寻找 whereHas 和 whereDoesntHave,将闭包传递给每个闭包以进行过滤:
Post::whereHas('tags', function($q) use($request){
if ($request->trending) {
$q->where('tag_type', $request->trending);
}
})
->whereDoesntHave('tags', function($q){
$q->where([
'tag_type' => 'restrict',
'tag_slug' => 'simple2'
]);
});
WhereHas 将 select 仅包含带有 tag_type === $request->trending 标签的帖子, WhereDoesntHave 将过滤掉标签为 tag_type === 'restricted' 和 tag_slug === 'simple2'.
的帖子