Php L5.6-数据透视表上的关系
我在轴上有一个关系表;我如何扩展它 例如: 商店:Php L5.6-数据透视表上的关系,php,laravel,eloquent,relation,laravel-5.6,Php,Laravel,Eloquent,Relation,Laravel 5.6,我在轴上有一个关系表;我如何扩展它 例如: 商店: 身份证 名字 产品: 身份证 名字 产品商店: 产品标识 店号 字段_1 字段2 第3场 表A\u id 表A: 身份证 名字 商店模型中的多对多关系为: class Shops extends Model { public function products() { return $this->belongsToMany('Products', 'product_shop', 'produ
- 身份证
- 名字
- 身份证
- 名字
- 产品标识
- 店号
- 字段_1
- 字段2
- 第3场
- 表A\u id
- 身份证
- 名字
商店
模型中的多对多关系为:
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\u shop.table\u id
,但我想展开外键并检索table\u A.name
;有办法吗
谢谢。您可以使用枢轴模型:
class ProductShopPivot extends\Lightning\Database\Eloquent\Relations\Pivot
{
公共职能表a()
{
返回$this->belongsTo(TableA::class);
}
}
类商店扩展模型
{
公共功能产品()
{
返回$this->belongtomany('Products'、'product\u shop'、'product\u id'、'shop\u id'))
->withPivot(
“字段_1”,
“字段_3”,
“字段_3”,
“表A\U id”
)
->as(“产品车间”)
->withTimestamps()
->使用(ProductShopPivot::类);
}
}
然后像这样访问它:
$shop->product_shop->tableA->name
不幸的是,没有办法急于加载
表a
关系。如果,使用->with('pivotmodel.endmodel')加载它,因为从技术上讲,可以通过hasMany查询将pivot模型作为一种关系。然后你可以加载它,这是一个很好的选择。我的意思是在使用产品
关系时没有任何方法。