L5.6 - 数据透视表上的关系



我在数据透视表上有一个关系;我如何扩展它?

例如:

商店

  • 编号
  • 名字

产品

  • 编号
  • 名字

product_shop

  • product_id
  • shop_id
  • field_1
  • field_2
  • field_3
  • table_A_id

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

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

谢谢。

您可以使用透视模型:

class ProductShopPivot extends IlluminateDatabaseEloquentRelationsPivot
{
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关系。

最新更新