首页 > 解决方案 > Laravel - Eager Loading BelongsToMany 关系

问题描述

我在两个实体/表之间有一对多的关系。

在此处输入图像描述


    /**
     * 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');
    }

当我想急切加载这种关系时,似乎有重复的查询在后台运行。我使用此代码急切加载我的关系:

    $automation = \App\Models\Automation::with('products')->whereId(1)->get()->first();
    dump($automation->products()->get());
    dump($automation->products()->get());
    dump($automation->products()->get());

有什么我想念的吗?

谢谢回复。

标签: phplaraveleager-loadinghas-and-belongs-to-manylaravel-relations

解决方案


渴望将负载关系加载到模型属性中。

您可以像访问此属性一样$automation->products- 无论她被调用多少次 - 查询将在急切的负载下执行一次

但是,当您调用 like ->products()->get()- eloquent 执行查询时,因为您告诉“现在的get()关系products()


推荐阅读