【问题标题】:PHP Laravel save() does not update recordPHP Laravel save() 不更新记录
【发布时间】:2017-12-15 08:40:28
【问题描述】:

看起来这不是新问题。但我还没有找到任何真正的解决方案。 这是我的预期代码:

$update_pet=pets::where("pet_id",$pet['pet_id'])->get();
if($update_pet->count()>0){
    $update_pet=$update_pet->first();
    $update_pet->pet_breed_id=$pet_new['pet_breed_id'];
    $update_pet->save();
}

我确信 $pet['pet_id'] 和 $pet_new['pet_breed_id'] 有价值。 而且我确信数据库中的表 pet_breeds 的主键为 pet_id。系统可以连接数据库,因为我可以获得pet_id和新的pet_breed_id。 而且我确定我已经覆盖了模型中的表名和主键值。

class pets extends Model
{
  protected $table="pets";
  protected $primaryKey="pet_id";
}

它甚至没有更新。 现在我只是直接使用 DB::update() 来运行更新查询来解决问题。 但我还是想知道为什么会这样?还是编码有问题?或者现在更新情况下不能使用保存功能?

【问题讨论】:

    标签: php laravel eloquent save


    【解决方案1】:

    为什么要把事情复杂化?

    pets::find($pet['pet_id'])->update(['pet_breed_id' => $pet_new['pet_breed_id']]);
    

    也可以包括这一行:

    protected $guarded = [];
    

    或者这个:

    protected $fillable = ['pet_breed_id'];
    

    在你的宠物模型类中。

    最后一件事,您应该以大写开头所有类名。并且型号名称不应该是复数。所以...

    class Pet extends Model
    

    【讨论】:

      【解决方案2】:

      尝试获取对象而不是集合:

      $pet = pets::find($pet['pet_id']);
      
      if (!is_null($pet)) {
          $update_pet->pet_breed_id = $pet_new['pet_breed_id'];
          $update_pet->save();
      }
      

      另外,通过将dd($pet); 放在代码的第一行之后,确保您获得了正确的对象。

      【讨论】:

      • 我已经测试过了,效果很好。非常感谢。 ^_^
      【解决方案3】:

      您只需将 get() 更改为 first(),它只会返回一个数据。

      $update_pet=pets::where("pet_id",$pet['pet_id'])->first();
      if($update_pet->count()>0){
          $update_pet=$update_pet->first();
          $update_pet->pet_breed_id=$pet_new['pet_breed_id'];
          $update_pet->save();
      }e
      

      或者如果你需要更新所有符合where条件的记录,使用foreach

      $update_pet=pets::where("pet_id",$pet['pet_id'])->get();
      foreach ($update_pet as $pet) {
          if($pet->count()>0){
              $pet=$update_pet->first();
              $pet->pet_breed_id=$pet_new['pet_breed_id'];
              $pet->save();
          }
      }
      

      【讨论】:

        【解决方案4】:

        您使用 get 方法将结果作为数组提供,因此不要使用第一种方法。如果 pet_id 是您的主键。

        $update_pet=pets::where("pet_id",$pet['pet_id'])->first();
        if($update_pet->count()>0){
           $update_pet=$update_pet->first();
           $update_pet->pet_breed_id=$pet_new['pet_breed_id'];
           $update_pet->save();
        }
        

        你在做什么 $update_pet->first() 在第 3 行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-20
          • 1970-01-01
          • 2016-06-12
          • 2020-05-30
          • 2022-01-12
          • 2020-09-24
          • 1970-01-01
          • 2023-03-28
          相关资源
          最近更新 更多