这些是我的表格many-to-many
:
[products
和suppliers
,但是我需要将数据透视表(product_supplier)关联到名为payment_supplier
的表。
产品型号
public function suppliers(){
return $this->belongsToMany('App\Supplier');
}
供应商型号
public function products(){
return $this->belongsToMany('App\Product');
}
但是我需要将枢轴product_supplier关联到payment_supplier表,就像在图中所描述的那样
在这种情况下,您可以使用数据透视模型。
# Product Model
public function suppliers() {
return $this->belongsToMany(Supplier::class)->using(ProductSupplier::class);
}
# Supplier Model
public function products(){
return $this->belongsToMany(Product::class)->using(ProductSupplier::class);
}
# ProductSupplier Pivot Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ProductSupplier extends Pivot
{
public function payment_supplier()
{
return $this->hasMany(PaymentSupplier::class);
}
}
但是,这样做有一个很大的问题:您不能急于加载数据透视表的关系。并非没有替代(或包装)。
另一种解决方法是使用hasManyThrough
# Product Model
public function suppliers()
{
return $this->belongsToMany(Supplier::class)->using(ProductSupplier::class);
}
public function payment_suppliers()
{
return $this->hasManyThrough(PaymentSupplier::class, ProductSupplier::class);
}
# Supplier Model
public function products()
{
return $this->belongsToMany(Product::class)->using(ProductSupplier::class);
}
public function payment_suppliers()
{
return $this->hasManyThrough(PaymentSupplier::class, ProductSupplier::class);
}
这将为您提供单个供应商/产品的所有PaymentSupplier,因此您需要应用某种过滤。