是否可以将枢轴上的 table 与 eloquent ORM 相关联?

Is it possible to relate a table on a pivot one with eloquent ORM?

这些是我的 table many-to-many:

productssuppliers,但是我需要将枢轴 (product_supplier) 与名为 payment_supplier.

的 table 相关联

产品型号

 public function suppliers(){
    return $this->belongsToMany('App\Supplier');
}

供应商模型

 public function products(){
    return $this->belongsToMany('App\Product');
}

但我需要将枢轴 product_supplier 与 payment_supplier table 相关联,就像图表中描述的那样

在这种情况下,您可以使用枢轴模型。

# 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);
}

这会为您提供单个 Supplier/Product 的每个 PaymentSupplier,因此您需要应用某种过滤。