【问题标题】:Laravel: How to update a column value of selected records without using loop with Laravel's Eloquent/Fluent?Laravel:如何在不使用 Laravel 的 Eloquent/Fluent 循环的情况下更新选定记录的列值?
【发布时间】:2018-10-10 10:31:06
【问题描述】:

我们如何在不使用 Laravel 的 Eloquent/Fluent 循环的情况下更新数据库中所有选定行的列值。见下文。

适用于单条记录:

$singleUser = User::where('status', '=', '0')->find(1);

$singleUser->status = '1';

$singleUser->save();

但它不适用于多条记录。它显示"Method save does not exist."

$allUsers = User::where('status', '=', '0')->get();

$allUsers->status = '1';

$allUsers->save();

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    您可以像这样执行查询(所有status 列字段将被更新)

    DB::table('User')->update(['status ' => 1]);
    

    另一种方式(此查询只更新那些状态为 0 的记录)

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

    【讨论】:

    • 从表中提取后需要更新记录。意味着我只需要为我选择的那些记录更新状态。
    • 您选择了where status =0。在上述答案 (User::where('status', '=', 0)->update(['status' => 1])) 中,此查询仅更新 status0 的那些记录
    • 在更新用户状态 = 1 之前,我需要做一些事情(选择用户状态 = 0),这就是为什么我只想为所选用户更新。
    • 您可以使用User::whereKey($allUsers->pluck('id'))->update(...);
    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多