如何渴望对同一张表加载多个belongsTo关系?

问题描述 投票:0回答:1

[使用以下模型,用户与汽车的关系是2倍。两者都指向同一张表,但是使用不同的字段(daily_car_id + weekend_car_id):

class User extends Model
    public function dailyCar() {
        return $this->belongsTo(Car::class, 'daily_car_id', 'id');
    }
    public function weekendCar() {
        return $this->belongsTo(Car::class, 'weekend_car_id', 'id');
    }
}

除了渴望加载之外,这一切都很好用:

User::with(['dailyCar', 'weekendCar'])->findOrFail($id);

期望

# 10 is the weekend car id and 12 is the daily
SELECT * FROM `car` WHERE `car`.`id` in (10, 12)

实际结果(不正确意外)

# 10 is the weekend car id and 12 is the daily
SELECT * FROM `car` WHERE `car`.`id` in (10)
SELECT * FROM `car` WHERE `car`.`id` in (12)

当对同一个表使用多个belongsTo关系时,是否有一种渴望加载的方法?

laravel laravel-5 eloquent eager-loading
1个回答
0
投票

您可以更改对此的急切加载:

$user = User::find($id);
$car = Car::where('id', $user->dailyCar->id)->where('id', $user->weekendCar->id)->get();
© www.soinside.com 2019 - 2024. All rights reserved.