php - Laravel Eager loading with nested OR condition
Get the solution ↓↓↓$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:
whereHas('emails', function ($q)
{
$q->where(function ($q) {
$q->where('email','like',"%john%")
->orWhere('email','like','%mark%');
});
})
This is example query forwhereHas
with pivot table (belongsToMany
):
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
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.