phplaraveleager-loadinghas-and-belongs-to-manylaravel-relations

Laravel - Eager Loading BelongsToMany Relationship


I have one to many relationship between two entities/tables.

enter image description here


    /**
     * 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.


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() relation products() NOW"