php - how to use WHERE clause and WITH in Laravel
Get the solution ↓↓↓I'm working on a small project using{-code-1}
and i would like to know how can i use{-code-2}
clause for{-code-3}
this is mycode
$buildings = Building::with('{-code-3}')->get();
i have already tried :
$buildings = Building::with('{-code-3}')->where('name','=',5)->get();
but it applies for Building not for {-code-3}.
how can i apply {-code-2} clause for {-code-3} ?
Answer
Solution:
You can apply a Closure towith(...)
if you pass in an array using the following syntax:
Model::with(['relation_name' => function ($query) { ... }])
In your case, what you're looking for is:
$buildings = Building::with(['apartment' => function ($apartments) {
$apartments->where('name', 5); // if you don't pass an operator, it's assumed to be '='.
}])->get();
You can also write it like this using PHP 7.4 shorthand closures.
$buildings = Building::with(['apartment' => fn($apartments) => $apartments->where('name', 5)])->get();
https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads
Answer
Solution:
Try this
$buildings = App\Building::with(['apartment' => function ($query) {
$query->where('name', 5); .
}])->get();
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: property [id] does not exist on this collection instance.
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.