Laravel Eloquent关联查询结果无法获取content_type_id如何解决
从你打印的数组结构可以看出,chapter_content 是一个索引数组,目标字段content_type_id存放在该数组下标为0的元素中,你之前的写法都没有匹配到这个层级结构,所以报错。
直接取值写法
如果你确定chapter_content中一定存在至少一条数据,可以直接通过层级下标取值:
$contentTypeId = $courseChapters['chapter_content'][0]['content_type_id'];
容错写法
如果需要避免数据为空时报错,可以用Laravel自带的data_get辅助函数,取不到值时会默认返回null:
$contentTypeId = data_get($courseChapters, 'chapter_content.0.content_type_id');
遍历取值的正确写法
你之前的foreach遍历的是整个$courseChapters数组,遍历得到的是id、courseId等单字段值,自然无法取到关联字段的值。如果需要遍历chapter_content中的所有内容,正确写法如下:
foreach($courseChapters['chapter_content'] as $item) { $contentTypeId = $item['content_type_id']; // 后续业务逻辑 }
更推荐的Laravel风格写法
更推荐你在查询时不要直接转成数组,使用Laravel的集合操作会更灵活,查询代码可以改成:
$courseChapter = courseChapter::with(['chapterContent' => function ($q) use ($id) { $q->where('course_chapter_id', $id)->select('course_chapter_id','file_id','content_type_id'); }]) ->select('id','courseId', 'chapter_title', 'isExam', 'points') ->first();
取值时可以直接用对象语法,或者集合的first()方法:
// 写法1 $contentTypeId = $courseChapter->chapter_content[0]->content_type_id; // 写法2 容错性更高 $contentTypeId = optional($courseChapter->chapter_content->first())->content_type_id;
内容的提问来源于stack exchange,提问作者user17189691
相关产品推荐
相关产品推荐

