【问题标题】:Laravel relationship inactive parentLaravel 关系不活跃的父级
【发布时间】:2021-08-13 04:25:45
【问题描述】:

我的posts 表中有两个表postspost_translations,有一个名为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();

【问题讨论】:

  • 尝试使用whereHas(),然后在关闭时使用where('active', true)
  • 上面写着Call to a member function getRelationExistenceQuery() on array

标签: laravel


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多