如何使用 Laravel 的 Eloquent/Fluent 将每一行设置为相同的值?

我需要更新数据库中的所有行,以便它们的 所有中的某个特定字段等于一个值。举个例子。

假设我的数据库表是这样的:

身份证 资料 确认
1 有些数据 0
2 有些数据 1
3 有些数据 0

我想执行一个查询,将每行的确认字段设置为1。

我可以这样做:

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

但似乎还有更好的办法?只有一个查询,它只说“将每一行的‘已确认’字段设置为1”

Laravel 的雄辩/流利是否存在这样的疑问?

95399 次浏览

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));

You can do this with elquent (laravel 4):

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

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

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

You can do this to update all the records.

App\User::where('id', 'like', '%')->update(['confirmed' => 'string']);

Solution for updating all rows :

  1. Create an extra column ( like 'updateAll') and assign static value for all rows (like this 'updateAll' = '1' ) in mysql table.

  2. Add hidden input field with name="forUpdateAll" and value="forUpdateAllValue" ( to execute only specific code for updating all rows)

  3. Then for update(Request $request, $id) method add this code :
public function update(Request $request, $id){
if($request->get('forUpdateAll') == "forUpdateAllValue"){
$question = \App\YourModel::where('updateAll',$id)
->update([
'confirmed' => 1
]);


}else {
//other code ( update for unique record )
}
}
  1. Setup your form like this :
<form role="form" action="/examples/1" method="post">
\{\{ method_field('PATCH') }}
\{\{ csrf_field()}}
<input type="hidden" name="forUpdateAll" value="forUpdateAllValue">
<button type="submit" class="btn btn-primary">Submit</button>
</form>

Model::where('confirmed', 0)->update(['confirmed' => 1])

Update any column fileds

DB::table('your_table_name')->update(['any_column_name' => 'any value']);

This working for me :

   MyModel::query()->update(  ['confirmed' => 1] );

Update all fields using laravel eloquent:

Way -> 1

[Status-> Columns you want to update]

Model::where('status', '=', 1)->update(['status' => 0]);

Way -> 2

[Status-> Columns you want to update]

$allData = Model::where('status', 1)->get();
foreach ($allData as $data){
$data->status= 0;
$data->update();
}