我正在建立网络以与laravel点餐。如果用户将相同的食物添加到购物车中,食物的数量将会增加。我创建了3个模型:OrderDetail,OrderOptionDetail,SubOption
食物模型:
struct JobResponseDataObject: Codable {
var id: Int?
var requestId: String?
var businessName: String?
var businessEmail: String?
var title: String?
private enum CodingKeys: String, CodingKey {
case id = "id"
case requestId = "request_id"
case businessName = "business_name"
case businessEmail = "business_email"
case title = "title"
}
}
let json = JSON(responseJSON: jsonData)
do {
if let value = try? json.rawData(){
let response = try! JSONDecoder().decode([[JobResponseDataObject]].self, from: value)
}
} catch {
print(error.localizedDescription)
}
FoodOption模型:
public function food_options(){
return $this->hasMany(FoodOption::class);
}
public function order_detail(){
return $this->hasMany(OrderDetail::class);
}
OrderDetail模型:
public function sub_options(){
return $this->hasMany(SubOption::class);
}
OrderOptionDetail模型:
protected $fillable = [
'order_id','food_id', 'quantity'
];
public function order_option_detail(){
return $this->hasMany(OrderOptionDetail::class);
}
public function food(){
return $this->belongsTo(Food::class);
}
SubOption模型:
protected $fillable = [
'order_detail_id', 'option_id','sub_option_id'
];
public function sub_option(){
return $this->belongsTo(SubOption::class);
}
在控制器中:
use Translatable;
public $translatedAttributes = [
'name'
];
protected $fillable = [
'food_option_id',
'price'
];
例如:奶茶的FoodOption为Size,子选项为S($ 0),M($ 1),L($ 1.5)。在购物车中已经存在数量= 1的S奶茶。如果用户选择S奶茶,然后再次添加到购物车。数量将增加到2。 如何在控制器中检查这一点。非常感谢大家!
答案 0 :(得分:0)
您可以检查此订单是否存在,然后将其添加到数量中并保存,否则创建新记录,还需要显示所选选项的“ selected_option”输入:
$orderDetail = OrderDetail::where(['food_id' => $request->input('food'),
'order_id' => $order->id])->first();
$check = $orderDetail->sub_option->where("food_option_id",$request->input('selected_option'));
...
if($check->exists()){
//$orderDetail = OrderDetail::where(['food_id' => $request->input('food'),
//'order_id' => $order->id])->first();
$orderDetail1->quantity += 1;
$orderDetail1->save();
}else{
$orderDetail = new OrderDetail();
......
}