【问题标题】:Laravel Polymorphic Many To Many Fetch By Specific AssociationLaravel 多态多对多通过特定关联获取
【发布时间】:2017-07-20 06:42:48
【问题描述】:

我有一个简单多对多多态关系(如果可能的话):

作者: 在博客上,我们有帖子 => 可作者 在杂志上,文章 => 可作者

这两种关系都按预期/记录在案。我需要的是获取特定帖子类别的所有作者

我只有:Post::category('blue') Collection(类别是一个范围)。基于此,获得撰写“蓝帖”的作者的最佳方式是什么?

【问题讨论】:

  • 你想要加载特定类别的所有作者吗?
  • 正是...我想要一个在蓝色类别中有帖子的作者集合

标签: laravel eloquent octobercms


【解决方案1】:

您需要考虑在您的范围内使用has()whereHas() 查询方法。有关使用它们的详细说明,请参阅Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

基本上看起来像这样:

$authorsOfBluePosts = Author::whereHas('posts', function ($postsQuery) {
    $postsQuery->whereHas('category', function ($categoryQuery) {
        $categoryQuery->where('name', 'blue');
    });
})->get();

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多