按关系中的最新记录列排序

纳布

我有两个表(模型)VehicleRegistration车辆有许多注册,每个注册都有start_dateexpiry_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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章