首页 > 解决方案 > 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();

标签: laravel

解决方案


试试这个:

$post = PostTranslate::with('post')->whereSlug($slug)
->whereHas('post',function($q){
  $q->where('active', true);
})->first();

推荐阅读