【发布时间】:2019-12-14 03:21:27
【问题描述】:
我有 3 张桌子 - carts、cart_products 和 products。
它们的结构如下所示:
手推车:
id, employee_id, name, paid
购物车产品:
id, cart_id, product_id, amount
产品:
id, name, price
现在在我的代码中,我抓取了所有未付费的购物车:
$carts = Cart::where('paid', false)->select('id')->get();
并遍历它们:
foreach ($carts as $key) {
$cart_products = DB::table('cart_products')
->where('cart_id', $key->id)
->get();
$returnedCarts[] = [
'id' => $key->id,
'name' => $key->name,
'products'=> $cart_products
];
}
return response()->json($returnedCarts);
现在我的问题是如何更改包含 JSON 的产品:
{
"id": 1,
"name": null,
"products": [ //this is the cart_products table
{
"id": 1,
"cart_id": 1,
"product_id": 1,
"amount": 2,
"created_at": null,
"updated_at": null
}
]
},
进入这个:
{
"id": 1,
"name": null,
"products": [ //this is data from the products table
{
"product_id": 1,
"amount": 2, //but this is from the cart_products table
"name": "This product name",
"price" "$9,49"
}
]
},
在 foreach 循环中无需额外查询。我应该使用什么样的联接?我应该更改我的代码还是应该使用模型而不是 DB 外观?
任何帮助将不胜感激。
【问题讨论】:
标签: php sql laravel join eloquent