laravel model save 如果表没有ID字段会报错

1、问题

$model = Test::first();
$model->status = 2;
$model->save();

如果Test模型对应表没有ID字段,会报错

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update test set status = 2, test.updated_at = 2020-09-04 15:03:06 where id is null) in file D:\www\wb-mg\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 671

以上可以看出,save() 是通id字段去匹配更新数据的。

2、解决

2.1、添加 ID 字段

如果可能的话,最好在表中添加一个名为 id 的主键字段。这样可以符合 Laravel 的默认预期,并且在使用 save() 方法时不会出现问题。

2.2、 自定义主键字段

如果你不想使用 id 作为主键字段,你可以在模型中明确指定主键字段的名称。可以通过在模型类中添加 primaryKey 属性来指定主键字段的名称。例如:

class YourModel extends Model {
    protected $primaryKey = 'your_custom_primary_key';
}

这样,Laravel 将会将 your_custom_primary_key 字段视为主键,而不是默认的 id 字段。

2.3、 处理没有主键的情况

如果你的表确实没有主键字段,你可以在使用 save() 方法之前,确保模型对象具有一个有效的主键值。你可以通过手动设置模型的主键属性来实现。例如:

$model->your_custom_primary_key = $someValidPrimaryKeyValue;
$model->save();
posted @ 2020-09-04 15:09  pine007  阅读(519)  评论(0编辑  收藏  举报