让我以此帖子开头,我无法更改插入主键的方法。这是在遗留系统上开发的,我无法控制检索主键的方法,我只需要处理它。
我发现Laravel在使用create方法时不会使用集合主键值的观察者来更新集合主键。
这是我的情况(我缩小了模型和文件的空间):
迁移文件:
Schema::create('forms_maps', function (Blueprint $table) {
$table->integer('id')->unsigned();
$table->string('name');
});
ModelObserver.php:
public function creating(Model $model)
{
$countername = strtolower(class_basename(get_class($model))).'s_id';
$model->id = tap(\App\Models\OCounter::where('countername',$countername)->first())->increment('counterval')->fresh()->counterval;
Log::debug("Creating ". strtolower(class_basename(get_class($model))) . ": " . $model);
}
DatabaseSeeder.php:
$accountApp = \App\Models\FormsMap::create(['name' => 'Account Application']);
Log::debug("Created formsmap: " . $accountApp);
输出日志:
Creating formsmap: {"name":"Account Application","id":84}
Created formsmap: {"name":"Account Application","id":0}
从日志中可以看到,当使用create方法创建记录时,在观察者内部,我得到了正确的id;但是,该值不会传递回DatabaseSeeder中的集合。我看错了吗?我是否应该使用其他方法将值插入表中?我不想手动/内联插入此值,因为每个模型都必须注入此信息。
谢谢!
Helenr