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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15622710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:24:42  来源:igfitidea点击:

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

laraveleloquentfluentlaravel-3

提问by Pete

I need to update all of the rows in a database so that a particular field in allof 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.

我想执行一个查询,将每一行的确认字段设置为 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."

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

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

Laravel 的 Eloquent/Fluent 中是否存在这样的查询?

回答by Matt

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

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

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

回答by LHolleman

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.

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

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

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

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

or even better

甚至更好

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

回答by styryl

You can do this with elquent (laravel 4):

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

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

回答by Sambit Mohapatra

You can do this to update all the records.

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

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

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