我正在尝试使用多态关系来建立供应商
和产品
之间的多对多关系:
products
id
name
suppliers
id
name
product_supplier
id
product_id // belongsToMany easily takes care of this id
supplier_id // and this id
price // this can be fetched using withPivot('price')
deliverymethod_id // I'm having difficulties "joining" this one.
我对使用 belongsToMany()
充满信心,我可以轻松地执行以下操作:
public function products()
{
return $this
->belongsToMany('Supplier')
->withPivot('price');
}
但这里的问题是连接到关系表中的第三列:
deliverymethods
id
name
我不确定如何做到这一点。有人告诉我,多态关系就是我所追求的,但我不确定如何根据我的情况实现它们。
http://laravel.com/docs/4.2/eloquent#many-to-many-polymorphic-relations
根据文档,我必须重命名表列以包含 *able_id
和 *able_type
。这确实令人困惑。
我期待 Laravel 有类似 belongsToMany('Supplier')->withAlso('Deliverymethod')
最佳答案
恐怕该方法还不存在(还不?)。
我会手动填写第三个关系:
public function products()
{
return $this
->belongsToMany('Supplier')
->withPivot('price', 'delivermethod_id');
}
现在我可以访问通过 Supplier
获得的每个 Product
上的 ->pivot->deliverymethod_id
。
您甚至可以在 Product
模型中添加一个函数来自动填充此内容:
Class Product ... {
protected $appends = array('deliverymethod');
public function getDeliverymethodAttribute()
{
return Deliverymethod::find($this->pivot->delivermethod_id);
}
现在,每次您通过与供应商的关系请求产品时,它都会自动包含一个deliverymethod
属性以及其中的对象。
(要使其在直接获取 Product
时不引发错误,只需从 Product
模型中删除 $appends
变量,然后当您需要时手动调用 getDeliverymethodAttribute()
方法。)
有关多态关系的简短说明:
多态关系是指两个模型同时与第三个模型相关的关系。例如,User
和 Product
都可以拥有它们的Picture
。现在,拥有两个图片模型(UserPicture
和 ProductPicture
)是没有意义的,因为它们都具有相同的特征。这将是使用多态关系的完美理由,其中 Picture
可以同时属于 User
或 Product
.
但是,在您的情况下,Deliverymethod
直接应用于Supplier
和Product
之间的关系。因此,这不是多态关系起作用的地方,但它必须按照您的方式完成。
关于php - Laravel 中可以实现这种多对多关系吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27330336/