我有问题,如果仅在请求中获得值==颜色,我需要更新记录。我该怎么办?我有代码:
$shop->services()->updateOrCreate([
'user_id' => $user->id,
'shop_id' => $shop->id,
'service_data' => $request->service_type == 'color' ? : false, //do update for record only if service_data == 'color'
], [
'price' => $price,
'valid_until' => Carbon::now()->addDays($request->valid_until),
'service_data' => $request->service_data == 'color' ?: false, //do update for record only if service_data == 'color'
]);
我该怎么做?
答案 0 :(得分:0)
您可以使用when
:
$shop->services()->when($request->input('service_data', false) === 'color', function($query) {
return $query->update([
'user_id' => $user->id,
'shop_id' => $shop->id,
'service_data' => 'color'
], [
'price' => $price,
'valid_until' => Carbon::now()->addDays($request->valid_until),
'service_data' => 'color'
]);
})
->when($request->input('service_data', false) !== 'color', function($query) {
return $query->create([
'user_id' => $user->id,
'shop_id' => $shop->id,
'service_data' => false
], [
'price' => $price,
'valid_until' => Carbon::now()->addDays($request->valid_until),
'service_data' => false
]);
});
答案 1 :(得分:-1)
KISS原则->保持简单
if ($request->service_data == 'color') {
$shop->services()->updateOrCreate([
'user_id' => $user->id,
'shop_id' => $shop->id,
'service_data' => $request->service_type
'price' => $price,
'valid_until' => Carbon::now()->addDays($request->valid_until),
'service_data' => $request->service_data
]);
}