我在数据透视表上有关系;我怎么能扩展呢?
例如:
商店:
> id
>名字
产品:
> id
>名字
product_shop:
> product_id
> shop_id
> field_1
> field_2
> field_3
> table_A_id
TABLE_A:
> 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_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关系.