PHP Laravel的save()方法无法更新记录。

3

看起来这不是一个新的问题。但我还没有找到任何真正的解决方案。 这是我的代码,期望它能够工作:

$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。 我确定我已经在模型中重写了表名和primaryKey值。
class pets extends Model
{
  protected $table="pets";
  protected $primaryKey="pet_id";
}

甚至没有更新。目前我直接使用DB :: update()来运行更新查询以解决问题。但我仍然想知道为什么会发生这种情况?或者是代码有问题吗?或者在更新情况下不能使用保存函数?

4个回答

2

Why make things complicated?

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

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

Try to get an object instead of collection:

$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);来获取正确的对象。

1
我已经测试过了,完美地工作了。非常感谢。^_^ - Fenix Lam

1

您只需要将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();
    }
}

0

你正在使用 get 方法,它会将结果作为数组返回,因此不要使用 first 方法。如果 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();
}

你在第3行中执行的$update_pet->first()是什么东西?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接