Laravel 使用自定义 PK 数组销毁方法
Laravel destroy method with array of custom PK
在官方文档中我可以看到一个方法destroy
,你可以在其中放置一个主键列表,它会删除列表中的所有数据。
ModelName::destroy([1,2,3]);
但是如果我们有自定义PK呢?我试图用一个名为 code
的字段来做到这一点,它是一个字符串,但它说:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `paises` where `id` in ())
有没有办法告诉Laravel主键不叫id
?
类似
ModelName::destroy(['AL', 'ES', 'FR'], 'code');
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.
因此,在您的模型中:
class User extends Model
{
protected $primaryKey = 'yourPrimaryKey';
}
由于您使用的似乎是基于字符串的 PK,因此文档中的以下段落也是相关的。
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.
因此您的模型还应包括:
protected $incrementing = false;
protected $keyType = 'string';
在官方文档中我可以看到一个方法destroy
,你可以在其中放置一个主键列表,它会删除列表中的所有数据。
ModelName::destroy([1,2,3]);
但是如果我们有自定义PK呢?我试图用一个名为 code
的字段来做到这一点,它是一个字符串,但它说:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `paises` where `id` in ())
有没有办法告诉Laravel主键不叫id
?
类似
ModelName::destroy(['AL', 'ES', 'FR'], 'code');
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.
因此,在您的模型中:
class User extends Model
{
protected $primaryKey = 'yourPrimaryKey';
}
由于您使用的似乎是基于字符串的 PK,因此文档中的以下段落也是相关的。
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.
因此您的模型还应包括:
protected $incrementing = false;
protected $keyType = 'string';