How to generate a query to db if several “where” and “update” are added in the loop?

萝らか妹 提交于 2019-12-11 16:47:16

问题


I have a method with four incoming arrays.

The first two arrays $whereColumns[] and $updateColumns[] contain columns names.

The third column $whereFilters[] contains filters for where methods.

And the last one $updateFilters[] contains values for updating.

How can I generate only one search query with several where methods and several updated columns? Now I know only how create a query with several where methods in a loop.

for($i=0; $<count($whereColumns); $i++){
    $query->where($whereColumns[$i], '=', $whereFilters[$i]);
}
$result = $query->get();

But how to generate a query with update like this (but this doesn't work):

for($i=0; $i<count($updateColumns); $i++){
    $query->update($updateColumns[$i] => $updateFilters[$i]); 
} 
$result = $query->get();

Both of these loops should generate one search query in total for updating a table data.


回答1:


You can loop through your $updateColumns and create an array containing all columns and values like this: $updateArray = [$column[0] => $value[0], $column[1] => $value[1]];

Then you can put this whole array into the query

$query->update($updateArray);



来源:https://stackoverflow.com/questions/47479070/how-to-generate-a-query-to-db-if-several-where-and-update-are-added-in-the-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!