我一直在努力與Laravel的關係。我正在做一個簡單的網上商店。我有4個重要的表格:訂單,訂單規則,產品和用戶。Laravel 5.4返回刀片中的全部訂單
我已經插入訂單與拉拉維爾Shoppingcart這一切都很順利。但是現在我想再次獲得完整的訂單,所以我可以爲它製作一個PDF文件。
這是我的數據庫設計:https://i.stack.imgur.com/nfPJy.png
這是我的訂單模式:
public function orderRules()
{
return $this->hasMany(Order_rule::class, 'order_id', 'order_id');
}
public function locations()
{
return $this->belongsTo(Location::class, 'place_id');
}
public function users()
{
return $this->belongsTo(User::class, 'user_id');
}
這是我的控制器功能:
public function orders()
{
$user_id = Auth::id();
$orders = Order::with('orderRules')->with('locations')->with('users')->where('user_id', $user_id)->get();
dd($orders);
return view('orders', [
'orders' => $orders,
]);
}
這是我的結果我從dumpdata得到:
Collection {#239 ▼
#items: array:4 [▼
0 => Order {#224 ▶}
1 => Order {#225 ▶}
2 => Order {#226 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:3 [▼
"orderRules" => Collection {#220 ▼
#items: array:2 [▼
0 => Order_rule {#244 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▼
"id" => 23
"order_id" => 521056
"product_id" => 1
"quantity" => 2
"date" => "2017-06-16 14:21:22"
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => Order_rule {#245 ▶}
]
}
"locations" => Location {#233 ▶}
"users" => User {#219 ▶}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
3 => Order {#227 ▶}
]
}
我只是想通過orderRule表中的產品的名稱,但orderRule加入只給出了PRODUCT_ID。有人可以幫我弄這個嗎?提前致謝!
[有很多通過](https://laravel.com/docs/5.4/eloquent-relationships#has-many-through)關係是你想要的。 – lesssugar
您不需要訂單表上的order_id列,相關表格應該直接引用id。此外,請遵循命名約定和用戶location_id而不是place_id來引用網上商店。 – btl
@btl表的id始終是唯一的,每個表都需要一個主鍵?如果我刪除了order_id,那麼1個訂單隻能有1個產品...如果我錯了,請糾正我的錯誤。 – RichSwek