我有两个表(模型) 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我得到了数据,但顺序不对。
发布于 2019-12-27 18:22:34
最后,我像这样解决:
return Vehicle::join('registrations', 'vehicles.id','=','registrations.vehicle_id')
->has('activeRegistration')
->orderBy('registrations.expiry_date')
->limit(5)
->get();发布于 2019-12-27 10:06:09
您需要在latest方法中添加字段:
public function activeRegistration() :HasOne
{
return $this->hasOne(Registration::class)->latest('expiry_date');
}如果您想使用with('registration'),您需要像这样使用闭包:
$vehicles = Vehicle::with(['registration' => function($relation) {
$relation->orderBy('expiry_date', 'DESC')->first();
}])->take(5)->get();Laravel5.7及以后的
如果你想获得最后一次注册,你可以直接使用latest('expiry_date'),
它将自动转换为order by expiry_date desc
$vehicles = Vehicle::with(['registration' => function($relation) {
$relation->latest('expiry_date')->first();
}])->take(5)->get();发布于 2019-12-27 10:51:13
然后在集合中使用sortBy()函数
Vehicle::with(['activeRegistration'])
->all()
->sortByDest(function ($vehicle) {
return $vehicle->activeRegistration->expiry_date;
});https://stackoverflow.com/questions/59498962
复制相似问题