我有一个关系pivot桌子;我怎样才能扩展它?
例如:
shops:
products:
产品商店:
- 产品编号
- shop_id
- field_1
- field_2
- field_3
- 表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 \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
关系。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)