1 回答
TA贡献1784条经验 获得超9个赞
使用现在的代码,这些是正在执行的查询(由Laravel Debugbar显示给我):
select * from `carts` where `user_id` = 1
select * from `products` where `id` = 15
select * from `product_details` where `product_id` = 15 and `id` = 33
select * from `products` where `id` = 20
select * from `product_details` where `product_id` = 20 and `id` = 41
它看起来像正在为每一个执行一个单独的查询product和product_details记录; 效率不高。让我们试试这个:
$carts = Cart::where('user_id', Session::get('user_id'))
->with('product.details')
->get();
对于上述语句,需要以下Eloquent关系:
// Cart model
public function product() {
return $this->belongsTo('App\Product');
}
// Product model
public function details() {
return $this->hasOne('App\ProductDetails', 'product_id', 'id');
}
这看起来好多了;无论检索多少产品或产品详细信息记录,执行的查询都不超过 3 个。
select * from `carts` where `user_id` = 1
select * from `products` where `products`.`id` in (15, 20)
select * from `product_details` where `product_details`.`product_id` in (15, 20)
现在将模型属性与其关系的属性结合起来:
$data = [];
foreach ($carts as $key => $cart) {
$data[$key] = [
'product_name' => $cart->product->product_name,
'product_image' => $cart->product->product_image,
'product_id' => $cart->product_id,
'variation_id' => $cart->variation_id,
'original_price' => $cart->product->details->original_price,
'selling_price' => $cart->product->details->selling_price,
'discount_price' => $cart->product->details->discount_price,
'discount_percent' => $cart->product->details->discount_percent,
'product_stock' => $cart->product->details->product_stock,
'product_unit' => $cart->product->details->product_unit,
'product_unit_value' => $cart->product->details->product_unit_value,
'cart_quantity' => $cart->quantity,
];
}
- 1 回答
- 0 关注
- 185 浏览
添加回答
举报