【问题标题】:Laravel query builder - how to select a model whereHas one of multiple relationshipsLaravel 查询构建器 - 如何选择具有多个关系之一的模型
【发布时间】:2021-06-01 14:18:18
【问题描述】:

我有一个 Shop 模型,它可以具有三个关系:SpecialsDiscountsThrowOuts。我想选择所有在这三个关系中的任何一个中有数据的Shops,但屏蔽那些根本没有的。

我还想根据Shop 本身的属性来限制搜索结果:

Shop::where('state', $state)
    ->whereHas('Specials')
    ->whereHas('Discounts ')
    ->whereHas('ThrowOuts')

此查询要求所有关系都有数据 - 不能为空

Shop::where('state', $state)
    ->orWhereHas('Specials')
    ->orWhereHas('Discounts ')
    ->orWhereHas('ThrowOuts')

使用orWhereHas 会返回所有在这些关系中有任何数据的商店无论第一个“位置”是什么,因此我也可以从全国各地获得商店。

【问题讨论】:

    标签: laravel laravel-query-builder wherehas


    【解决方案1】:

    ...aa并且我刚刚回答了我自己的问题 - 将第一个 where 的结果分组,然后在该分组上运行关系查询:

    Shop::where('state', $state)
        ->where(function ($query) {
            return $query->orWhereHas('Specials')
                         ->orWhereHas('Discounts ')
                         ->orWhereHas('ThrowOuts');
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-02
      • 2021-08-31
      • 2021-12-28
      • 2018-03-01
      • 1970-01-01
      • 2018-09-08
      • 2019-04-24
      • 1970-01-01
      相关资源
      最近更新 更多