dthjnc306679 2019-04-26 08:23
浏览 82
已采纳

Laravel Create Method不返回Observer插入的主键值

Let me preface this post with, I cannot change the method of inserting the primary key. This is being developed on a legacy system and I have no control over the method of retrieving the primary key, I just have to deal with it.

I have found that Laravel will not update the collection primary key when using the create method, with an observer that inserts the primary key value.

Here is my scenario (I have shrunk the models and files for space):

migration file:

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);

The output log:

Creating formsmap: {"name":"Account Application","id":84}
Created formsmap: {"name":"Account Application","id":0}

As you can see from the log, when the record is created using the create method, inside of the observer, I am getting the proper id; however, that value is not being passed back to the collection in the DatabaseSeeder. Am I looking at this incorrectly? Should I be using something else to insert the values into the tables? I do not want to insert this value manually/inline because every model has to have this information injected.

Thanks!

展开全部

  • 写回答

1条回答 默认 最新

  • doulezhi5326 2019-04-26 08:49
    关注

    GRRR!!!! I do this every time! The answer is:

    The model needs to have the incrementing turned off.

    class FormsMap extends Model
    {
        public $timestamps = false;
        public $incrementing = false;
    
        ...
    }
    

    Heh!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部