作为标题, 我正在尝试使用多态关系获取数据的名称。
当我得到一个对象时,它的工作很完美。 但是当结果是多个对象时,情况并非如此。
这是我的尝试。
>>> $page = AppPageAtribut::first()
=> AppPageAtribut {#2863
id: 1,
page_id: 1,
watchable_id: 1,
watchable_type: "AppCategory",
created_at: "2018-09-11 11:03:20",
updated_at: "2018-09-11 11:03:20",
}
>>> $page->watchable
=> AppCategory {#2857
id: 1,
name: "Series",
created_at: "2018-09-11 11:01:46",
updated_at: "2018-09-11 11:01:46",
}
因为我使用"id"来获取数据。
接下来,我尝试使用等于page id
的条件获取所有数据page_id
。
>>> $page = AppPageAtribut::where('page_id', 1)->get()
=> IlluminateDatabaseEloquentCollection {#2859
all: [
AppPageAtribut {#2860
id: 1,
page_id: 1,
watchable_id: 1,
watchable_type: "AppCategory",
created_at: "2018-09-11 11:03:20",
updated_at: "2018-09-11 11:03:20",
},
AppPageAtribut {#2861
id: 2,
page_id: 1,
watchable_id: 2,
watchable_type: "AppUser",
created_at: "2018-09-11 11:03:40",
updated_at: "2018-09-11 11:03:40",
},
],
}
>>> $page->watchable
Exception with message 'Property [watchable] does not exist on this collection instance.'
结果在这里。
Exception with message 'Property [watchable] does not exist on this collection instance.'
如果有多个像上面这样的对象,如何获取名称?...
请使用
$page = AppPageAtribut::where('page_id', 1)->first();
dd($page->watchable);
因为get()
会得到一个集合数组。
在@Jigar评论和@Adlan答案中提到。
因为 get 返回一个collection
,并且首先返回一个single
模型实例。
由于它array collections
需要使用forloop来获取每个模型的属性。
所以代码将是。
$page = AppPageAtribut::where('page_id', 1)->get()
然后
foreach($page->pageatribut as $p)
{
echo $p->watchable->name;
}
它返回每个集合的所有名称。
中医网.