【发布时间】:2014-09-19 15:55:16
【问题描述】:
我目前有 4 张桌子:
accessories
id
products
id
product_accessory
id
product_id
accessory_id
product_accessory_adaptor
id
product_accessory_id
将它们映射到 Eloquent 模型给了我
自定义枢轴模型:
class ProductAccessory extends Pivot {
protected $table = 'product_accessory';
public function product()
{
return $this->belongsTo('Product');
}
public function accessory()
{
return $this->belongsTo('Accessory');
}
public function adaptors() {
return $this->hasMany('Adaptor', 'product_accessory_id');
}
}
产品及配件型号
class Accessory extends Eloquent {
public function products()
{
return $this->belongsToMany('Product', 'product_accessory', 'accessory_id', 'product_id')->withPivot();
}
public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Product) {
return new ProductAccessory($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
public function adaptors()
{
return $this->hasManyThrough('Adaptor', 'ProductAccessory', 'accessory_id', 'product_accessory_id');
}
}
class Product extends Eloquent {
public function accessories()
{
return $this->belongsToMany('Accessory', 'product_accessory', 'product_id', 'accessory_id')->withPivot();
}
public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Accessory) {
return new ProductAccessory($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
public function adaptors()
{
return $this->hasManyThrough('Adaptor', 'ProductAccessory', 'product_id', 'product_accessory_id');
}
}
适配器型号:
class Adaptor extends Eloquent {
protected $table = 'product_accessory_adaptor';
public function productAccessory() {
return $this->belongsTo('ProductAccessory');
}
}
这就是我需要的。急切地为所有带有配件的产品加载属于其枢轴的适配器。我已经尝试过这样的事情,但我不知道如何传递枢轴 ID
在产品模型中
public function accessories()
{
return $this->belongsToMany('Compatibility\Accessory', 'product_accessory', 'product_id', 'accessory_id')
->withPivot('id', 'accessory_disclaimer')
->withTimestamps()
->with(['adaptors' => function ($q) {
$q->where('product_accessory_id', $this->pivot->id);
}]);
}
有没有人知道如何做到这一点?我应该用 $this->pivot->id 替换什么?
【问题讨论】:
-
请参考您之前关于 Pivot 模型的问题中的 cmets。希望一切都清楚。