首页 > 解决方案 > Laravel 在中间数据透视表上过滤最大日期

问题描述

我有一个定义的多对多关系(在发票和班次之间)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'user_id',
        'date_ins',
        'tas',
    ];

    public function user()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    /**
     * The roles that belong to the invoice.
     */
    public function shifts()
    {
        return $this->belongsToMany(Shift::class, 'invoice_shift')
        ->withPivot(['invoice_id','shift_id', 'shift_taken_id', 'shift_swapped_date','shift_taken_date', 'tas','msg','status_tas']);
    }

}

然后转移模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shift extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'code',
        'description',
    ];
    /**
     * The users that belong to the role.
     */
    public function invoices()
    {
        return $this->belongsToMany(Invoice::class, 'invoice_shift');
    }
}

在数据透视表中,我还有一个名为 shift_swapped_date 的列,我只想为所有发票检索在数据透视表中具有该日期最大值的一行。我在控制器中尝试过

$invoices = Invoice::with('shifts')
->get();   
$invoices->max('pivot.shift_swapped_date');

但它不起作用我不知道该怎么做...... Thx

标签: phplaraveleloquent

解决方案


如果这不起作用,请尝试运行以下解决方案:

$invoices = Invoice::with(['shifts' => function($query) {

    $query->max('shift_swapped_date');

}])->get();

推荐阅读