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

Laravel中with()预加载关联时get()指定字段返回null如何解决

问题原因

当使用Laravel的with预加载关联数据时,belongsTo关联需要主表中存储的外键字段值来匹配关联表的主键,你在get()方法中只指定了查询post_status和created_at两个字段,没有带上关联RequestThing所需的外键request_id,导致框架无法匹配到对应的关联数据,最终requests字段返回null。

解决方案

只需要把外键request_id加入到主表的查询字段列表中即可,修改后代码如下:

public function bedRequest()
{    
    $bedRequests = BedRequest::where(['approved' => 1, 'post_status' => 0])
        ->with('requests')
        ->get(['post_status', 'created_at', 'request_id']);
    return $bedRequests;
}

修改后返回结果就会包含你需要的post_status、created_at字段,以及完整的requests关联数据,不会额外返回BedRequest的其他字段。

额外优化(可选)

如果你不需要关联表RequestThing的全部字段,也可以在预加载时指定关联表的查询字段,注意必须带上关联表的主键id才能正常匹配:

// 示例:只查询关联表的id、name、age、gender四个字段
$bedRequests = BedRequest::where(['approved' => 1, 'post_status' => 0])
    ->with('requests:id,name,age,gender')
    ->get(['post_status', 'created_at', 'request_id']);

补充注意:你当前定义的RequestThing模型中的bedRequests关联类型有误,按照业务逻辑一个请求单应该对应多个床位申请,应该把belongsTo改为hasMany,如果后续你要反向查询会用到这个关联,记得调整代码。

内容的提问来源于stack exchange,提问作者Sagun Raj Lage

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 08:54:06