Use an array in Laravel update query

2020-07-20 04:44发布

问题:

I would like to push an array in Where Clause of Laravel Update Query.

Here is the update query.

DB::table('users')->where('id', 1)->update(array('votes' => 1));

Is it possible to use the query like below ??

$array_of_ids;
DB::table('users')->where($array_of_ids)->update(array('votes' => 1));

Thanks

回答1:

Simply use whereIn:

$array_of_ids;
DB::table('users')->whereIn('id', $array_of_ids)->update(array('votes' => 1));

Please read the documentation carefully. In this case, all kinds of where statements are documented here: Query Builder - Selects



回答2:

using the query builder: The query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:

DB::table('users')
        ->where('id', 1)
        ->update(['votes' => 1]);