php - Laravel - Eager Loading BelongsToMany Relationship
Get the solution ↓↓↓I have one to many relationship between two entities/tables.
/**
* Get all of the products.
*/
public function products()
{
return $this->belongsToMany(Product::class)->select(
[
'products.id',
'products.title',
'products.sku',
'automation_products.automation_id as auto_id',
'display_order',
]
)->orderBy('display_order');
}
When I want eager load this relationship, it seems like there are duplicate queries running in the background. I use this code to eager load my relation:
$automation = \App\Models\Automation::with('products')->whereId(1)->get()->first();
dump($automation->products()->get());
dump($automation->products()->get());
dump($automation->products()->get());
is there something I am missing?
Thanks for the reply.
Answer
Solution:
Eager loading load relation into model property.
You can access this property like$automation->products
- no matter how many times she is called - query will be executed ONE time with eager load.
But, when you call like->products()->get()
- eloquent execute query because you tell "get()
relationproducts()
NOW"
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: too few arguments to function laravel
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.