Laravel雄辩的关系变形多数据不起作用

问题描述 投票:0回答:2

作为标题,我试图使用多态关系来获取数据的名称。

当我得到一个单一的物体时,它的工作是完美但是当结果多个对象时,它不是。

在这里我的尝试。

>>> $page = App\PageAtribut::first()
=> App\PageAtribut {#2863
     id: 1,
     page_id: 1,
     watchable_id: 1,
     watchable_type: "App\Category",
     created_at: "2018-09-11 11:03:20",
     updated_at: "2018-09-11 11:03:20",
   }
>>> $page->watchable
=> App\Category {#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 = App\PageAtribut::where('page_id', 1)->get()
=> Illuminate\Database\Eloquent\Collection {#2859
     all: [
       App\PageAtribut {#2860
         id: 1,
         page_id: 1,
         watchable_id: 1,
         watchable_type: "App\Category",
         created_at: "2018-09-11 11:03:20",
         updated_at: "2018-09-11 11:03:20",
       },
       App\PageAtribut {#2861
         id: 2,
         page_id: 1,
         watchable_id: 2,
         watchable_type: "App\User",
         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.'

如果上面有多个对象,如何获取名称?...

php eloquent laravel-5.5
2个回答
0
投票

请用

$page = App\PageAtribut::where('page_id', 1)->first();
dd($page->watchable);

因为get()会得到一系列的集合。


0
投票

在@Jigar评论和@Adlan答案中提到。

因为get返回一个collection并首先返回一个single模型实例。

由于它的array collections需要使用for循环来获取每个模型的属性。

所以代码就是。

$page = App\PageAtribut::where('page_id', 1)->get()

然后

foreach($page->pageatribut  as $p)
{ 
    echo $p->watchable->name; 
}

它返回每个集合的所有名称。

CMIIW。

© www.soinside.com 2019 - 2024. All rights reserved.