【发布时间】:2018-03-20 08:29:32
【问题描述】:
在我的项目中,我有一个多态关系。这种关系如下:
Plugins
id - integer
composer_package - string
Themes
id - integer
composer_package - string
Products
id - integer
name - text
...
commentable_id - integer
commentable_type - string
当我需要显示属于主题的所有产品时,我会执行以下操作:
$themes = DB::table('products')->orderBy('id', 'asc')->where('productable_type', Theme::class)->get();
上面的代码为我提供了productable_type 字段填充有App/Theme 的所有产品的列表,我使用像@foreach($themes as $theme) 这样的foreach 循环显示它们。现在我的问题是。
我需要从属于该产品的主题表中获取composer_package。所以比如说。我从产品表中得到一个产品,其中productable_id 为3。我想要主题表中ID 为3 的composer_package 字段的值。当我执行{{ $theme->products->composer_package }} 或{{ $theme->composer_package }} 时,它给了我错误Undefined property这是什么原因?
这是我的产品模型
public function product()
{
return $this->morphTo();
}
public function order_items()
{
return $this->hasMany(Orderitems::class);
}
这是我的主题模型
public function webshops()
{
return $this->hasMany(Webshop::class);
}
public function products()
{
return $this->morphMany(Product::class, 'productable');
}
提前致谢!
【问题讨论】: