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
相关产品推荐
相关产品推荐

