从 Eloquent 模型事件中获取新创建的 ID
Getting newly created ID from Eloquent Model Event
我有一个带有非自动递增主键的模型 ID
,我已经在我的模型中定义了它。
protected $primaryKey = "ID";
在我的 AppServiceProvider 中,我有一些模型侦听器。
Product::created(function ($product){
dd($product);
});
所以如果我去插入一个新行:
$NewProduct = new Product;
$NewProduct->ID = 12345;
$NewProduct->Name = "Test";
事件被触发,所以 dd
在 AppServiceProvider 中得到 运行。 ID 按预期进入数据库,但我输出的 $product
数组显示 ID 为 0.
为什么 ID 以 12345 进入数据库时显示为 0?
我不确定,但您是否在模型中将增量设置为 false?
public $incrementing = false;
您应该将自动增量 属性 显式设置为 false 以使其工作。在您的模型中:
protected $primaryKey = "ID";
public $incrementing = false;
Primary Keys
Eloquent will also assume that each table has a primary key column
named id. You may define a $primaryKey property to override this
convention.
In addition, Eloquent assumes that the primary key is an incrementing
integer value. If you wish to use a non-incrementing primary key, you
must set the $incrementing property on your model to false.
我有一个带有非自动递增主键的模型 ID
,我已经在我的模型中定义了它。
protected $primaryKey = "ID";
在我的 AppServiceProvider 中,我有一些模型侦听器。
Product::created(function ($product){
dd($product);
});
所以如果我去插入一个新行:
$NewProduct = new Product;
$NewProduct->ID = 12345;
$NewProduct->Name = "Test";
事件被触发,所以 dd
在 AppServiceProvider 中得到 运行。 ID 按预期进入数据库,但我输出的 $product
数组显示 ID 为 0.
为什么 ID 以 12345 进入数据库时显示为 0?
我不确定,但您是否在模型中将增量设置为 false?
public $incrementing = false;
您应该将自动增量 属性 显式设置为 false 以使其工作。在您的模型中:
protected $primaryKey = "ID";
public $incrementing = false;
Primary Keys
Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.
In addition, Eloquent assumes that the primary key is an incrementing integer value. If you wish to use a non-incrementing primary key, you must set the $incrementing property on your model to false.