【问题标题】:Unable to fetch data from Laravel Eloquent Relationships无法从 Laravel Eloquent 关系中获取数据
【发布时间】:2021-12-10 22:50:00
【问题描述】:

我想访问content_type_id 的值。我尝试过$courseChapters['chapter_content']['content_type_id']$courseChapters['content_type_id']$courseChapters[0]['content_type_id']$courseChapters['chapterContent']['content_type_id']。所有这些都显示错误ErrorException: Undefined index: content_type_id 。我还在下面评论过的foreach 循环中尝试了所有内容。没有任何效果。谁能告诉我如何解决这个问题?

/*foreach($courseChapters as $key){
   // $contentTypeId=$key->first(); //Call to a member function first() on int
  //  $contentTypeId=$key->first()->chapter_content; //Call to a member function first() on int
  //  $contentTypeId=$key['chapter_content']['content_type_id']; //error - Illegal string offset
  //  $contentTypeId=$key[0]['content_type_id']; ////error - Illegal string offset
  //  $contentTypeId=$key['content_type_id']; //error - Illegal string offset 'content_type_id' 
  }*/
$courseChapters = 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')
            ->get()->toArray()[0];

标题 ## dd($courseChapters); 显示如下所示的数组:

array:6 [
  "id" => 4
  "courseId" => 24
  "chapter_title" => "chapter1"
  "isExam" => false
  "points" => 8
  "chapter_content" => array:1 [
    0 => array:3 [
      "course_chapter_id" => 4
      "file_id" => 1
      "content_type_id" => 1
    ]
  ]
]

【问题讨论】:

  • chapter_content 有多条记录,所以您没有按上述方式访问。
  • @Smithiam 那么,我怎样才能访问它?请告诉我
  • $courseChapters['chapter_content']->pluck('content_type_id')->implode(',');
  • @Smithiam 这显示了错误Call to a member function pluck() on array

标签: php laravel eloquent laravel-8 eloquent-relationship


【解决方案1】:

这样访问第一个

echo $courseChapters['chapter_content'][0]['content_type_id'];

或像这样访问所有这些

foreach ($courseChapters['chapter_content'] as $chapter) {
    echo $chapter['content_type_id'];
}

【讨论】:

  • 如果 chapter_content 数组中有多个记录怎么办?这仅适用于第一个键
  • 只使用一个foreach。我将编辑我的答案。
  • 没错
  • 我可以使用您的第一种方法本身访问content_type_id。我如何访问course_chapter_id
  • 只需将其用作键即可。 $courseChapters['chapter_content'][0]['course_chapter_id']
猜你喜欢
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 2020-10-08
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2017-05-01
相关资源
最近更新 更多