ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

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 中是否存在这样的查询?


M
Matt

为了让这个线程保持最新,你可以直接使用 Eloquent 模型更新所有行:

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

这就是我要找的!谢谢!
我更喜欢使用 Eloquent。这一定是答案
这是最好的方法。只是为 query() 部分添加一些解释,如果您正在执行类似 Model::where('foo', '=', 'bar')->update(['confirmed' => 1]) 的操作,则不需要 query() 部分。但是要更新没有 where() 的所有行,需要 query() 来获取查询构建器对象。
请注意,这与 DB::table('table') 的不同之处在于它不考虑软删除的行!为此,您可以使用:Model::query()->withTrashed()->update(['confirmed' => 1]);
L
LHolleman

好吧,一个简单的答案:不,你不能用雄辩的。一个模型代表数据库中的 1 行,如果他们实现它就没有意义。

但是,有一种方法可以使用 fluent 来做到这一点:

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

甚至更好

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

这行得通,但是 Matt 的较新答案是更简洁的方法,因为该答案使用 Eloquent,因此您不必依赖于知道表名并求助于数据库构建器函数。
s
styryl

你可以用 elquent (laravel 4) 做到这一点:

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

I
Ihtisham Hussain

更新所有行的解决方案:

创建一个额外的列(如'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>

M
MRMP

更新任何列文件

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

F
Faran

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


A
Abd Abughazaleh

这对我有用:

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

S
Sambit Mohapatra

您可以这样做来更新所有记录。

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