我有这个查询
DB::table('pro_orders_has_passengers')
->where('title_name','MR.')
->update([
'title_name' => 'mr',
]);
DB::table('pro_orders_has_passengers')
->where('title_name','MRS.')
->update([
'title_name' => 'mrs',
]);
DB::table('pro_orders_has_passengers')
->where('title_name','Miss')
->update([
'title_name' => 'ms',
]);
DB::table('pro_orders_has_passengers')
->where('title_name','Girl')
->update([
'title_name' => 'girl',
]);
DB::table('pro_orders_has_passengers')
->where('title_name','Boy')
->update([
'title_name' => 'boy',
]);
我得到正确的结果。但是我希望在一个查询中得到这个结果。 像这样
$titlename = ['MR.','MRS.','Miss','Girl','Boy'];
DB::table('pro_orders_has_passengers')
->where('title_name',$titlename)
->update([
........
]);
我该怎么做?谢谢您的回复。
答案 0 :(得分:1)
我认为您可以通过这种方式实现您想要的
$titlename = ['MR.','MRS.','Miss','Girl','Boy'];
for($i=0; $i < count($titlename);$i++) {
DB::table('pro_orders_has_passengers')
->where('title_name',$titlename[$i])
->update(['title_name' => strtolower(str_replace('.', '' , $titlename[$i]))]);
}
或使用foreach循环,以提高代码的可读性:
$titlenames = ['MR.','MRS.','Miss','Girl','Boy'];
foreach($titlenames as $titlename) {
DB::table('pro_orders_has_passengers')
->where('title_name',$titlename)
->update(['title_name' => strtolower(str_replace('.', '' , $titlename))]);
}
答案 1 :(得分:0)
$titlename = ['mr' => 'MR.','mrs' => 'MRS.','ms' => 'Miss','girl' => 'Girl', 'boy' => 'Boy'];
$update_query = "UPDATE pro_orders_has_passengers SET title_name = CASE";
foreach ($titlename as $new_title => $title) {
$update_query = $update_query . " WHEN title_name = '$title' THEN '$new_title'";
}
$update_query = $update_query . " END WHERE title_name IN ('".implode(array_values($titlename), '\',\'')."')";
\DB::statement($update_query);
尝试这种方式。它会帮助您进行批量更新。
最终产量将
更新pro_orders_has_passengers SET title_name =标题名称为CASE =“ MR”。然后在title_name ='MRS'时'mr'。 THEN'mrs'当title_name ='小姐'THEN'ms'当title_name ='女孩'THEN'girl'当title_name ='男孩'THEN'男孩'结束title_name IN (“ MR。”,“ MRS。”,“小姐”,“女孩”,“男孩”)
答案 2 :(得分:0)
尝试这个。有关更多信息,请参见以下链接
1。I want to use CASE statement to update some records in sql server 2005
2。运行一般性声明:https://laravel.com/docs/5.7/database
DB::statement(
UPDATE pro_orders_has_passengers
SET title_name = CASE
WHEN title_name = 'Mr.' THEN 'mr'
WHEN title_name = 'Mrs.' THEN 'mrs'
//-------Others cases-----//
ELSE LASTNAME
END
WHERE title_name IN ('Mr.', 'Mrs.', .....)
);