我目前有以下模型:Product
在这个模型中,我有:
public function productDetails()
{
return $this->morphMany(Productable::class, 'productable');
}
DB记录如下。在Product中我有:
id: 71,
product_name: 'this is a test',
description: 'some stuff',
然后我有一个模型Productable
与
public function productable()
{
return $this->morphTo();
}
数据库中的数据为:
62 71 AppModelsMedia 1 2021-03-04 19:53:22 2021-03-04 19:53:22
63 71 AppModelsMedia 7 2021-03-04 19:53:22 2021-03-04 19:53:22
64 71 AppModelsMedia 8 2021-03-04 19:53:22 2021-03-04 19:53:22
65 71 AppModelsMedia 9 2021-03-04 19:53:22 2021-03-04 19:53:22
66 71 AppModelsAttribute 3 2021-03-04 19:53:22 2021-03-04 19:53:22
67 71 AppModelsCoating 2 2021-03-04 19:53:22 2021-03-04 19:53:22
68 71 AppModelsProductImage 9 2021-03-04 19:53:22 2021-03-04 19:53:22
其中71为product_id
然后尝试像这样检索数据:
$product = Product::find(71);
dd($product->productDetails);
返回一个空数组。我肯定我错过了一些东西,只是不确定是什么。
一对多多态关系类似于典型的一对多关系;但是,使用单个关联,子模型可以属于不止一种类型的模型。这就是正在发生的事情,数据库中的记录属于其他模型。
您正在尝试获取属于其他模型的记录。Media
,Attribute
,Coating
,ProductImage
。为此,必须将记录分配给Product
模型。
那么数据库中的记录应该如下所示:
62 71 AppModelsProduct 1 2021-03-04 19:53:22 2021-03-04 19:53:22
63 71 AppModelsProduct 7 2021-03-04 19:53:22 2021-03-04 19:53:22
64 71 AppModelsProduct 8 2021-03-04 19:53:22 2021-03-04 19:53:22
65 71 AppModelsProduct 9 2021-03-04 19:53:22 2021-03-04 19:53:22
66 71 AppModelsProduct 3 2021-03-04 19:53:22 2021-03-04 19:53:22
67 71 AppModelsProduct 2 2021-03-04 19:53:22 2021-03-04 19:53:22
68 71 AppModelsProduct 9 2021-03-04 19:53:22 2021-03-04 19:53:22