[英]Unable to fetch data from Laravel eloquent relationships array
i've an array like below for $response
.我有一个像下面这样的数组用于$response
。 i wanted to fetch the user
field alone & files
field lying inside the user
from it .我想单独获取user
字段和user
内部的files
字段。 i tried like $response['user']
& $response['user']['files']
, it shows the error undefined index
.我试过像$response['user']
& $response['user']['files']
,它显示了错误undefined index
。 How can i achieve this?我怎样才能做到这一点?
[
{
"id": 14,
"userId": 1,
"courseDisplayName": "yuu",
"aboutCourse": "kljkl",
"user": {
"id": 1,
"name": "admin",
"profilePicId": 93,
"aboutUser": null,
"files": {
"id": 93,
"FilePath": "contentq/contentqFiles/XwyC6JHK5T/Account.png"
}
},
"files": null
}
]
What am trying to do here is that ,the input couresId
is array like [14,15]
, So for each item in the array ,i wanted to fetch data from Course
, user
& files
tables , for which the id
of Course
table has the value taken in input, userId
of course
table has the value of id
in user
table & fileId
of course
table has the value of id
in files
table.我在这里尝试做的是,输入couresId
是像[14,15]
这样的数组,所以对于数组中的每个项目,我想从Course
、 user
和files
表中获取数据,其中Course
表的id
具有在输入所采取的值, userId
的course
表具有的值id
在user
表& fileId
的course
表具有的值id
在files
表中。 The realtions user
& files
are defined in the Course
model. Realtions user
和files
在Course
模型中定义。
$response=null;
foreach($request->courseId as $key => $row){
$response[] = Course::with([
'user' => function($q)
{
$q->with('files:id,FilePath')->select('id', 'name' , 'profilePicId','aboutUser');
},'files:id,FilePath'])
->where('id',$row)
->get()
->makeHidden(['subjectId','skillId','courseUniqueName','active','created_at','updated_at','deleted_at','publish','course_patterns_id','paid_status','fileId','updatedBy']);
}
**EDIT**
//$res=[];
foreach($response as $row){
$res['user'] = $row->user; // error- Property [user] does not exist on this collection instance
$res['user'] = $row->first()->user;// works , but it will show only 1 set of data. i wanted all sets of data.
}
$response is an array or collection of array. $response 是一个数组或数组的集合。 you can't access $response['user'] without looping it.你不能在不循环的情况下访问 $response['user'] 。 Either call $response->first() or make a foreach to loop through $response要么调用 $response->first() 要么做一个 foreach 来循环 $response
Way One:方式一:
$user = $response->first()->user;
$files = $response->first()->files;
Way Two:方式二:
foreach($response as $row){
$user = $row->user;
$files = $row->files;
// use dd() these to see what you get
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.