我有两个表(模型)Vehicle
和Registration
。车辆有许多注册,每个注册都有start_date
,expiry_date
我需要得到所有具有最后注册的车辆expiry_date
。这是我的Vehicle
模型部分:
/**
* @return HasMany
*/
public function registrations() :HasMany
{
return $this->hasMany(Registration::class);
}
/**
* @return HasOne
*/
public function activeRegistration() :HasOne
{
return $this->hasOne(Registration::class)->latest();
}
我尝试解决这样的问题:
Vehicle::with('activeRegistration')->get()->sortBy('activeRegistration.expiry_date')->take(5) // I need only 5 records
但这没有按我预期的那样工作。这是我的刀片文件的一部分:
@foreach($registrationsVehicle as $vehicle)
<tr>
<td>{{ $vehicle->registration }}</td>
<td>{{ $vehicle->vehicleBrand->name }}</td>
<td>{{ $vehicle->model }}</td>
<td>{{ optional($vehicle->activeRegistration)->start_date }}</td>
<td>{{ optional($vehicle->activeRegistration)->expiry_date }}</td>
</tr>
@endforeach
我得到数据,但顺序不正确。
最后,我这样解决:
return Vehicle::join('registrations', 'vehicles.id','=','registrations.vehicle_id')
->has('activeRegistration')
->orderBy('registrations.expiry_date')
->limit(5)
->get();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句