You need to enable JavaScript to run this app. 访问Eloquent集合时如何动态设置父表?Laravel Livewire开发问题
优惠活动
大模型
产品
解决方案
定价
更多

访问Eloquent集合时如何动态设置父表?Laravel Livewire开发问题

问题定位与修复方案

报错触发根源

抛出"Trying to get property 'id' of non-object"的直接原因是:$colaboradores->Niveis->$string 返回了null或非对象类型,后续尝试访问->id属性时触发PHP错误。
结合调试输出验证:

  • $colaboradores->Niveis 本身是正常的关联模型实例,初始化逻辑无问题
  • 动态拼接得到的$string字段值,和Niveis模型上定义的可访问属性名不匹配,导致动态读取属性时未获取到对应的关联模型对象

常见的不匹配原因:

  • 从数据库拉取的表名规则是复数格式(如intervencoes_xxx),但模型上定义的关联属性是单数命名(如intervencao_xxx),命名规则不一致
  • 表名提取过程中存在多余字符、前后空格,导致implode拼接后的字符串和实际属性名存在偏差

修复实现

  1. 优化表名拉取流程,去掉多余的数组转换拼接逻辑,避免引入异常字符:
$colaboradores = Colaboradore::where('email', '=', Auth::user()->email)->first();
$tables = DB::connection('mysql2')->select("SHOW TABLES LIKE 'intervencoes\_%'");

$tableNames = [];
foreach ($tables as $tableItem) {
    $tableArr = (array)$tableItem;
    $tableNames[] = reset($tableArr);
}
  1. 遍历取值时增加前置判断,对齐命名规则,避免非对象访问直接触发报错:
foreach ($tableNames as $tableName) {
    // 对齐命名规则:根据实际模型的属性命名规则做映射转换
    $attributeName = str_replace('intervencoes_', 'intervencao_', $tableName);
    // 前置判断属性存在且为有效模型实例
    if (!isset($colaboradores->Niveis->$attributeName) || !$colaboradores->Niveis->$attributeName) {
        continue;
    }
    $test = $colaboradores->Niveis->$attributeName->id;
}
  1. 兼容Laravel动态关联读取规范的写法,避免魔术方法返回空值引发的异常:
foreach ($tableNames as $tableName) {
    $attributeName = str_replace('intervencoes_', 'intervencao_', $tableName);
    // 用模型内置的关联读取方法取值,稳定性更高
    $targetRelation = $colaboradores->Niveis->getRelationValue($attributeName);
    if ($targetRelation) {
        $test = $targetRelation->id;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 23:45:01