laravel - Laravel 关系不活跃的父级
问题描述
我有 2 个表posts
,并且post_translations
在我的posts
表中有一个名为的布尔列,如果父活动为 false ,active
我希望防止子行post_translations
可见。post
$post = PostTranslate::whereSlug($slug)->with(['post'=> function($q) {
$q->where('active', true);
}])->first();
上面的代码仅在帖子(父级)处于非活动状态时阻止包含翻译结果,但它不会阻止翻译本身。
逻辑
我在这里寻求的是,
如果父级(帖子)处于非活动状态,则不显示任何子级(post_translations),否则可以根据请求提供翻译。
有什么建议可以解决我的查询吗?
更新
我设法让它与 sql 查询一起工作,但我不会关闭这个问题,因为我正在寻找基于模型的解决方案,无论如何这是它目前的工作方式
$post = DB::table('post_translates')
->where('post_translates.slug', $slug)
->join('posts', 'posts.id', 'post_translates.post_id')
->where('posts.active', true)
->first();
解决方案
试试这个:
$post = PostTranslate::with('post')->whereSlug($slug)
->whereHas('post',function($q){
$q->where('active', true);
})->first();
推荐阅读
- python - Python如何使用for循环对齐文本?
- python - 如何在 Python 中生成具有 4 位字符串和 4 位数字的随机码?
- php - rest api codeigniter 结果缺失列
- python - 考虑每个计数重新计算平均值
- python - 如何将base64字符串作为图像保存到django python中的本地服务器
- wordpress - 覆盖 global/wrapper-start.php 不起作用
- reactjs - 接收排版文件的尝试导入错误
- sql-server - SQL,有没有办法遍历一列中的所有行然后计算值,然后遍历另一列中的所有行并计算无联合
- lua - 如何使工作区中的点击检测器在 StarterGui 中启用脚本?(罗布洛克斯工作室)
- go - 如何有条件地搜索与gorm具有多对多关系的数据