本文介紹了L5.6 - 數據透視表的關系的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我在樞軸表上有一個關系;我如何擴展它?
I've a relation on a pivot table; how I can expand It?
例如:
商店:
- id
- 姓名
產品:
- id
- 姓名
product_shop:
- product_id
- shop_id
- field_1
- field_2
- field_3
- table_A_id
table_A:
- id
- 姓名
Shops
模型中的多對多關系是:
The relation Many-to-Many in the Shops
Model is:
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();
}
}
檢索所有數據的查詢是:
and the query to retrieve all data is:
class GetData extends Model {
public static function getAll() {
$query = Shops::with(
'products'
)->get();
}
}
這會返回product_shop.table_A_id
,但我想擴展外鍵并檢索table_A.name
;有辦法嗎?
This return the product_shop.table_A_id
but I'd like to expand the foreign key and retrieve table_A.name
; is there a way?
謝謝.
推薦答案
您可以使用樞軸模型:
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
關系.
Unfortunately, there is no way to eager load the tableA
relation.
這篇關于L5.6 - 數據透視表的關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!