我有这样的代码:
$id = 5;
$a = 1;
$b = ($a === 2 ? 1 : 2);
DB::table('table')->where('id', $id)->where('value', $a)->update(['new_value' => 1]);
DB::table('table')->where('id', $id)->where('value', $b)->update(['new_value' => 2]);
是否可以在1中进行2次查询?
答案 0 :(得分:3)
您无法使用查询构建器。请改用DB::statement
:
DB::statement('UPDATE table SET new_value = CASE
WHEN value = ? THEN ?
WHEN value = ? THEN ?
END WHERE id = ?', [
$a, 1,
$b, 2,
$id,
]);
答案 1 :(得分:0)
在mysql查询中,您可以通过以下查询来实现:
$mysqlQuery = "UPDATE table1
SET new_value = IF(id=".$id ." AND value=".$a.",1, IF(id=".$id." AND value=".$b.",2,new_value))";
Note:If you want this mysql query to be written in some framework specific query then you can convert it as per your framework syntax or documentation.
答案 2 :(得分:0)
AFAIK,而不是laravel流利。有2个不同的查询具有不同的更新值。但是,您可以将其变为可重复使用的功能。
public function updateNewValue($id, $value, $newValue)
{
return DB::table('table')
->where('id', $id)
->where('value', $value)
->update(['new_value' => $newValue]);
}
或者,您可以使用switch语句将其合并为一个,具体取决于new_value
:
$query = DB::table('table')->where('id', $id);
switch($newValue)
{
case 1:
return $query->where('value', $a)->update(['new_value' => $newValue]);
case 2:
return $query->where('value', $b)->update(['new_value' => $newValue]);
}