欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel model update Eloquent ORM update

$affectedRows = User::where('votes', '>', 100)->update(array('status' => 2));


How to set every row to the same value with Laravel's Eloquent/Fluent?

I need to update all of the rows in a database so that a particular field in all of them is equal to a single value. Here's an example.

Let's say my database table is like so:

id    |   data   |  confirmed
1     | someData |      0
2     | someData |      1
3     | someData |      0

I want to perform a query that sets the confirmed field of every row to 1.

I could do it this way:

$rows = MyModel::where('confirmed', '=', '0')->get();
foreach($rows as $row) {
    $row->confirmed = 0;
    $row->save();
}

But it seems like there would be a better way? A single query that would just say "set every row's 'confirmed' field to 1."

Does such a query exist in Laravel's Eloquent/Fluent?

正确答案

Well, an easy answer: no, you can't with eloquent. A model represents 1 row in the database, it wouldn't make sense if they implemented this.

However, there is a way to do this with fluent:

$affected = DB::table('table')->update(array('confirmed' => 1));

or even better

$affected = DB::table('table')->where('confirmed', '=', 0)->update(array('confirmed' => 1));
shareimprove this answer
 

Just to keep this thread current, you can update all rows against an Eloquent model directly using:

Model::query()->update(['confirmed' => 1]);
shareimprove this answer
 

You can do this with elquent (laravel 4):

MyModel::where('confirmed', '=', 0)->update(['confirmed' => 1])
shareimprove this answer
 

来自  https://stackoverflow.com/questions/15622710/how-to-set-every-row-to-the-same-value-with-laravels-el...


普通分类: