【问题标题】:Laravel - Eager Loading BelongsToMany RelationshipLaravel - Eager Loading BelongsToMany 关系
【发布时间】:2021-10-17 19:44:40
【问题描述】:

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


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

我有什么遗漏吗?

感谢您的回复。

【问题讨论】:

  • 你认为他们为什么会跑?
  • 他们正在运行,非常好,请不要与变量名混淆,问题主要围绕一次又一次执行的查询

标签: php laravel eager-loading has-and-belongs-to-many laravel-relations


【解决方案1】:

将负载关系急切加载到模型属性中。

您可以像$automation->products 一样访问此属性 - 无论她被调用多少次 - 查询都将执行 ONE 次并立即加载。

但是,当您像 ->products()->get() 这样调用时 - 雄辩地执行查询,因为您告诉“get() 关系 products() NOW”

【讨论】:

  • 当我做 $automation->products 时它返回null
  • 发现关系名必须和表名一致,谢谢帮助
猜你喜欢
  • 2019-10-20
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2017-05-23
相关资源
最近更新 更多