我需要更新数据库中的所有行,以便所有行中的特定字段等于单个值。这是一个例子。
假设我的数据库表是这样的:
id 数据确认 1 someData 0 2 someData 1 3 someData 0
我想执行一个查询,将每一行的已确认字段设置为 1。
我可以这样做:
$rows = MyModel::where('confirmed', '=', '0')->get();
foreach($rows as $row) {
$row->confirmed = 0;
$row->save();
}
但似乎有更好的方法?一个查询只会说“将每一行的‘确认’字段设置为 1”。
Laravel 的 Eloquent/Fluent 中是否存在这样的查询?
为了让这个线程保持最新,你可以直接使用 Eloquent 模型更新所有行:
Model::query()->update(['confirmed' => 1]);
好吧,一个简单的答案:不,你不能用雄辩的。一个模型代表数据库中的 1 行,如果他们实现它就没有意义。
但是,有一种方法可以使用 fluent 来做到这一点:
$affected = DB::table('table')->update(array('confirmed' => 1));
甚至更好
$affected = DB::table('table')->where('confirmed', '=', 0)->update(array('confirmed' => 1));
你可以用 elquent (laravel 4) 做到这一点:
MyModel::where('confirmed', '=', 0)->update(['confirmed' => 1])
更新所有行的解决方案:
创建一个额外的列(如'updateAll')并为mysql表中的所有行(如'updateAll' = '1')分配静态值。添加带有 name="forUpdateAll" 和 value="forUpdateAllValue" 的隐藏输入字段(仅执行更新所有行的特定代码)然后为 update(Request $request, $id) 方法添加此代码:
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 )
}
}
像这样设置您的表单:
<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>
更新任何列文件
DB::table('your_table_name')->update(['any_column_name' => 'any value']);
模型::where('confirmed', 0)->update(['confirmed' => 1])
这对我有用:
MyModel::query()->update( ['confirmed' => 1] );
您可以这样做来更新所有记录。
App\User::where('id', 'like', '%')->update(['confirmed' => 'string']);
不定期副业成功案例分享
query()
部分添加一些解释,如果您正在执行类似Model::where('foo', '=', 'bar')->update(['confirmed' => 1])
的操作,则不需要query()
部分。但是要更新没有where()
的所有行,需要query()
来获取查询构建器对象。DB::table('table')
的不同之处在于它不考虑软删除的行!为此,您可以使用:Model::query()->withTrashed()->update(['confirmed' => 1]);