拉拉维尔 具有嵌套 OR 条件的紧急加载


Laravel Eager loading with nested OR condition

$query = LeadsModel::with(
                            array(
                                    'emails' => function ($q) use ($inputs) 
                                    {
                                        $q->orwhere('email','like',"%john%");
                                        $q->orwhere('email','like',"%mark%");
                                    }
                                )
                            )
                            ->whereHas
                            (
                                'emails', function ($q) use ($inputs) 
                                {
                                    $q->orwhere('email','like',"%john%");
                                    $q->orwhere('email','like','%mark%');
                                }
                            );
    $res = $query->get();
    display_output($res);
    return;

上面的代码仅返回所有记录,不对结果应用任何条件。我不确定出了什么问题。我想要的是为与父表关联的子表在查询中添加条件,但将返回应用条件的父项和子项数据

附加问题:

  • 如何在预先加载的嵌套条件中添加多个 OR 条件?
  • 如何控制条件的优先级? 假设我将在相同的优先级中具有 2 或 3 个条件,并且在嵌套的紧急加载条件中我将具有 AND 条件的另一个条件

更新

这仍然记录所有数据,不应用任何条件。

    $query = LeadsModel::with(
                            array(
                                    'emails' => function ($q) use ($inputs) 
                                    {
                                        $q->orWhere('email','like',"%john%");
                                        $q->orWhere('email','like',"%james%");
                                    }
                                )
                            )
                            ->whereHas
                            (
                                'emails', function ($q) use ($inputs) 
                                {
                                    $q->where('email','like',"%john%")->orWhere('email','like','%james%');
                                }
                            );
    $res = $query->get();
    display_output($res);
    return;

在普通的SQL中,我想它会是

选择潜在客户。,lead_detail_emails。从潜在客户,lead_detail_emails在哪里leads.id = lead_detail_emails.lead_id 和(lead_detail_emails.email like '%john%' 或 lead_detail_emails.email like '%james%'(;

您需要嵌套在以下位置:

whereHas('emails', function ($q)
{
    $q->where(function ($q) {
      $q->where('email','like',"%john%")
        ->orWhere('email','like','%mark%');
    });
})

这是使用数据透视表(belongsToMany(whereHas的示例查询:

select * from `table` 
    where `table`.`deleted_at` is null 
        and (select count(*) from `related_table` inner join `pivot_table` on `related_table`.`id` = `pivot_table`.`related_id` 
    where `pivot_table`.`user_id` = `table`.`id` 
        and (`some_field` like ? or `some_field` like ?)) >= 1