You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 11:如何在with()中获取指定列非空的模型最后一条记录

解决方案

你只需要在关联定义里先通过where添加done_by不为NULL的约束,再调用latestOfMany()即可,这样关联查询时只会返回满足条件的最新记录:

public function firstCheckedChecklistItem() 
{ 
    return $this->hasOne('App\Models\CheckedChecklistItem')
                ->whereNotNull('done_by')
                ->latestOfMany(); 
}

原理说明

latestOfMany()是基于前面构建的查询约束来筛选最新记录的,先通过whereNotNull('done_by')过滤掉done_by为NULL的记录,再从中取最新的那一条,完全满足你在with()关联中实现需求的要求。

原有的调用代码无需修改,依然可以正常使用:

$groupMachines = Machine::where('group_id', $group_id)->with('machineType.checklistGroup.currentChecklists.checklistItem.firstCheckedChecklistItem')->get();

内容的提问来源于stack exchange,提问作者Matthias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 09:10:54