Laravel渴望加载不必要的查询

时间:2018-11-29 11:12:41

标签: laravel eloquent eager-loading

因此,假设我们有2个模型“ A”和“ B”。 模型“ A”通过不同的foreignKey与“ B”模型具有两个belongsTo关系。 例如,在数据库中,我们有2条记录,结构为

 id | first_id | second_id
 1        1          2
 2        2          1

问题是当我这样做时:

 A::with(['first', 'second'])->get()

它调用两个相同的sql查询以获取关系

select * from `B` where `B`.`id` in (1, 2) and `B`.`deleted_at` is null
select * from `B` where `B`.`id` in (1, 2) and `B`.`deleted_at` is null

那如何避免呢?

P.S模型班

class A extends Model {
    public function first() {
        return $this->belongsTo(B::class, 'first_id');
    }

    public function second() {
        return $this->belongsTo(B::class, 'second_id');
    }
}

b模型为空

0 个答案:

没有答案