php - 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
解决方案
如果这不起作用,请尝试运行以下解决方案:
$invoices = Invoice::with(['shifts' => function($query) {
$query->max('shift_swapped_date');
}])->get();
推荐阅读
- php - 如何在 Django 中发送文件以响应?
- android - 即使在 BIOS 中启用了虚拟技术,它也无法正常工作
- typescript - 无法导入无类型的 npm 模块
- tensorflow - 这是编写神经网络预测代码
- gun - 处理连接/断开状态并在 GUN 中获取在线用户
- node.js - 在 linux 上使用 clasp 时 node-v57-linux-x64-glibc/grpc_node.node 丢失
- python - 从网页抓取时如何识别要指定的 HTML 标签或类?
- batch-file - 通过批处理文件识别 Windows 上的版本
- php - 从下拉菜单中获取输入到 php
- javascript - 从导航栏过滤反应组件