我有一張名為 invoices、orders、games、products、users 的表格
這是我的發票表結構
id name order_id
這是我的訂單表結構
id name game_id product_id user_id
這是我的游戲表結構
id name display_name
這是我的產品表結構
id product_sku name price profit
正如您在這種情況下看到的那樣,我正在嘗試下訂單后生成發票的訂單。在發票中,我想顯示下訂單的游戲名稱、產品名稱、價格和用戶。我應該使用什么關系?它是hasMany 還是belongsToMany?還是我應該制作另一個名為 invoice_order 的表?
更新!
我忘了顯示我的表 game_product,我已經在游戲和產品表之間建立了 belongsToMany 關系。
id game_id product_id
Cmiiw
uj5u.com熱心網友回復:
我認為您應該具有以下表結構:
訂單(從發票重命名)
id name user_id
order_product(樞軸)
order_id product_id
游戲
id name display_name
產品
id product_sku name price profit game_id
這些應該是關系:
訂購型號
public function products() {
return $this->belongsToMany(Product::class);
}
public function user() {
return $this->belongsTo(User::class);
}
游戲模型
public function product() {
return $this->hasMany(Product::class);
}
public function orders() {
return $this->hasManyThrough(Order::class, Product::class);
}
產品型號
public function game() {
return $this->belongsTo(Game::class);
}
public function orders() {
return $this->belongsToMany(Order::class);
}
這樣您就可以生成發票:
$invoiceData = Order::with([ 'user', 'products', 'products.game' ])->find($id);
這將包含$invoiceData物件內訂單的所有必要資訊,例如下訂單$invoiceData->user的用戶和$invoiceData->products訂購產品的集合。
請注意,將資料中心作為額外的資料中心欄位通常是一種很好的做法,price因為order_product人們購買商品的價格并不總是該商品的價格,因此您可以獲得有關商品價格的資訊出售的價格,而不是出售的物品和今天的價格。
uj5u.com熱心網友回復:
一個簡單的屬于關系足以滿足您的案例場景
發票.php
public function order(){
return $this->belongsTo(Order::class);
}
訂單.php
public function game(){
return $this->belongsTo(Game::class)->select('id', 'name')
}
public function product(){
return $this->belongsTo(Product::class)->select('id', 'name')
}
控制器.php
Invoice::with(['order' => function($q) {
return $q->with('game', 'product');
})->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432543.html
標籤:拉拉维尔
