php - 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;
The code above only returns all record and no condition applied to the result. I am not sure what is wrong. What I want is to add conditions in the query for the child table associated with the parent but will return the parent and child data where the condition is applied
additional question:
- How can I add several OR condition in nested condition in eager loading?
- how can I control the precedence of the condition? lets say I will have 2 or 3 condition in the same precedence and I will have another condition with AND condition in a nested eager loading condition
updated
This still records all data, no condition applied.
$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;
in normal sql i guess it would be
select leads.,lead_detail_emails. from leads, lead_detail_emails where leads.id = lead_detail_emails.lead_id and (lead_detail_emails.email like '%john%' OR lead_detail_emails.email like '%james%');
Answer
Solution:
You need nested where:
This is example query for
whereHas
with pivot table (belongsToMany
):