简体   繁体   English

无法从 Laravel Eloquent 关系中获取数据

[英]Unable to fetch data from Laravel Eloquent Relationships

i wanted access the value of content_type_id .i tried like $courseChapters['chapter_content']['content_type_id'] , $courseChapters['content_type_id'] , $courseChapters[0]['content_type_id'] & $courseChapters['chapterContent']['content_type_id'] .All these shows the error ErrorException: Undefined index: content_type_id .我想访问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 I also tried everything in the foreach loop i've commented below.我还尝试了我在下面评论的foreach循环中的所有内容。 Nothing works.什么都行不通。 Can someone tell me how to fix this?有人可以告诉我如何解决这个问题吗?

$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];

 /*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' 
  }*/

dd($courseChapters); shows array like given below:显示如下所示的数组:

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
    ]
  ]
]

Like this to access the first像这样访问第一个

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

or like this to access all of them或者像这样访问所有这些

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM