laravel hasOne但有多个相同的ID

时间:2019-09-04 11:39:06

标签: php laravel laravel-5 eloquent

我有车辆表。 (id, name, make)

我有vehicle_prices表(id, vehicle_id, mileage, price)

现在,可能在vehicle_prices中,我可能多次具有相同的vehicle_id,但它们的里程数却不同。因为车辆价格因里程而异。因此,我对vehicle_id和里程具有唯一的索引。由于vehicle_prices中有多个vehicle_id,我决定使用hasMany关系。所以这是我正在做的事情。

$vehicle = App\Http\Models\Vehicle::with([
            'prices' => function($query){
                $query->where('milleage', 1000)->latest('id')->first();
            })
        ])->where('id', 1)->first();

现在的事情是$ vehicle-> prices现在是一个数组,该数组中始终有1个对象。为什么它不仅是对象而是数组?我猜那是因为hasMany的关系。

即使hasMany可能在hasOne中重复出现,我是否应该拥有vehicle_id或将其更改为vehicle_prices

1 个答案:

答案 0 :(得分:0)

如果要获取一个对象,请使用:

 $vehicle->prices()->first();

Documentation

相关问题