【发布时间】:2022-01-13 11:04:56
【问题描述】:
我有 2 个模型 => post 和 tag(多对多关系),标签也有 2 种类型,如“趋势”和“限制”
标签模型表 : id - tag_type - tag_title - tag_slug
public function getTags()
{
return $this->belongsToMany(Tag::class, 'tags_posts', 'post_id', 'tag_id');
}
我需要获得以下帖子:当 $request->trending 存在时,返回具有 tag_type == "trending" 和 tag_title == $request->trending Also 的帖子(这是't 有条件且始终检查)除了具有 tag_type == "restrict" 和 tag_slug == "simple2" 的帖子
我需要雄辩的 laravel 而不是 php 数据库,优化很重要
感谢一百万
【问题讨论】:
-
旁注:关系方法应命名为
tags,枢轴应命名为post_tag以遵循约定;那么你只需要belongsToMany的 1 个参数 -
谢谢,名字没问题,他们可以工作
-
这是什么意思:“当
$trending="simple"存在时”?那个变量是从哪里来的? -
@lagbox - 是的,它是可变的,从请求中获取:$trending = $request->trending;
-
听起来您正在寻找
whereHas和whereDoesntHave...它在 Eloquent Relations 文档中,Querying Relationship Existence/Absence
标签: laravel database eloquent tags