L5.6 - 枢轴关系 table

L5.6 - Relation on pivot table

我在枢轴 table 上建立了关系;我该如何扩展它?

例如:

店铺:

产品:

product_shop:

table_A:

Shops 模型中的多对多关系是:

class Shops extends Model {
    public function products()
    {
        return $this->belongsToMany('Products', 'product_shop', 'product_id', 'shop_id')->withPivot(
            'field_1',
            'field_3',
            'field_3',
            'table_A_id'
            )
            ->as('product_shop')
            ->withTimestamps();
    }

}

检索所有数据的查询是:

class GetData extends Model {
     public static function getAll() {
         $query = Shops::with(
            'products'
            )->get();
     }
}

这 return product_shop.table_A_id 但我想扩展外键并检索 table_A.name;有办法吗?

谢谢。

您可以使用枢轴模型:

class ProductShopPivot extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    public function tableA()
    {
        return $this->belongsTo(TableA::class);
    }
}

class Shops extends Model
{
    public function products()
    {
        return $this->belongsToMany('Products', 'product_shop', 'product_id', 'shop_id')
            ->withPivot(
                'field_1',
                'field_3',
                'field_3',
                'table_A_id'
            )
            ->as('product_shop')
            ->withTimestamps()
            ->using(ProductShopPivot::class);
    }
}

然后像这样访问它:

$shop->product_shop->tableA->name

不幸的是,无法预先加载 tableA 关系。