dthjnc306679 2019-04-26 16: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 16: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!

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

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画