简体   繁体   English

在模型上调用 save() 将更新数据库中的每一行

[英]Calling save() on a model will update every row in the database

I've got the following function in a migration file.我在迁移文件中有以下功能。 The migration is to add a new column, and then update the columns of the existing entries:迁移是添加一个新列,然后更新现有条目的列:

<?php

private function updatePlans()
{
    $plans = PlanProvider::query()->get();

    foreach ($plans as $plan) {
        $plan->num_adults = 1;

        if (stripos($plan->rate_name, 'couple') !== false) {
            $plan->num_adults = 2;
        }
        $plan->save();
    }
}

Now, what's happening here is that when I call save() , it's updating EVERY model, instead of the one inside the loop.现在,这里发生的事情是,当我调用save() ,它正在更新每个模型,而不是循环内的模型。 I have a similar function for another migration, and it works as expected.我有另一个迁移的类似功能,它按预期工作。 Why would this update every model rather than just the one?为什么这会更新每个模型而不仅仅是一个模型?

$plans is a Collection that contains all your "plans". $plans是一个包含所有“计划”的集合。 Your $plan->save();你的$plan->save(); is outside your if conditions, so obviously it updates every single row, no matter if it has 1 or 2 num_adults在你的if条件之外,所以很明显它更新每一行,不管它有 1 还是 2 num_adults

 public function store(Request $request)
    {


        $this->validate($request,[
            'email' => 'required|email|unique:subscribers'
        ]);

        $subscriber = new Subscriber();
        $subscriber->email = $request->email;
        $subscriber->save();
        Toastr::success('You are Successfully Added Our Subscriber List:)','Success');
        return redirect()->back();

   }

you can try this你可以试试这个

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlanProvider extends Model
{

    protected $table = 'plan_provider';
    
    protected $guarded = [];
    public $timestamps = false;
}


private function updatePlans()
{
    $plans = PlanProvider::findOrFail(id);
    $plans->num_adults = 1;
    $plans->save();
    
    return redirect()->back();  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM