用户注册时自动创建关联Profile记录失败的问题排查与解决方案咨询
用户注册时自动创建关联Profile记录失败的问题排查与解决方案咨询
嘿各位,最近做用户注册功能时卡壳了:用户注册成功后,我需要自动生成一条关联的Profile记录(通过user_id和User表关联),但不管怎么调试,Profile表的字段就是写不进去。手动在MySQL里修改Profile的字段值完全没问题,而且user_id的数值也是正确的,但程序就是没法把数据插入到Profile的对应字段里,这可愁死我了。
先贴一下我的数据库迁移代码,方便大家帮我看看有没有潜在问题:
Profile表迁移代码
public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 10, 'unsigned' => true, 'auto_increment' => true, ], 'firstname' => [ 'type' => 'VARCHAR', 'constraint' => '128', 'null' => true, ], 'lastname' => [ 'type' => 'VARCHAR', 'constraint' => '128', 'null' => true, ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => '128', 'null' => true, ], 'phone' => [ 'type' => 'VARCHAR', 'constraint' => '128', 'null' => true, ], 'description' => [ 'type' => 'TEXT', 'constraint' => '128', 'null' => true, ], 'date_birth' => [ 'type' => 'DATE', 'null' => true, ], 'avatar' => [ 'type' => 'TEXT', 'null' => true, ], 'user_id' => [ 'type' => 'int', 'constraint' => 11, 'unsigned' => true, 'null' => false, ], ]); $this->forge->addForeignKey('user_id', 'user', 'id', '', 'CASCADE'); $this->forge->addPrimaryKey('id')->addUniqueKey('user_id'); $this->forge->createTable('profile'); } public function down() { $this->forge->dropTable('profile'); }
User表迁移代码
public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 10, 'unsigned' => true, 'auto_increment' => true, ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '128', 'null' => false, ], 'password_hash' => [ 'type' => 'VARCHAR', 'constraint' => '255', 'null' => false, ] ]); $this->forge->addPrimaryKey('id')->addUniqueKey('name'); $this->forge->createTable('user', true); } public function down() { $this->forge->dropTable('user'); }
后来我自己摸索了半天,猜测是数据库写入的优先级或者逻辑有问题,换成upsert方法后居然成功把字段值写入Profile表了!下面是我修改后的注册方法代码:
调整后的注册方法代码
public function create_account() { $user = $this->request->getPost(); $avatar = $user['avatar']; if ($user) { if ($this->model->insert($user)) { $user_id = $this->request->getPost('name'); $login = $this->model->where('name', $user_id)->first(); $session = session(); $session->set('user_id', $login->id); $session->set('user_name', $login->name); if (session()->has('user_id') && $this->profile->upsert(['avatar' => $avatar, 'user_id' => session()->get('user_id')])) { $session->set('id', $login->id); return redirect()->to('/home')->with('success', ['Вы успешно авторизовались']); } } else { return redirect()->back()->with('errors', $this->model->errors())->with('warning', 'Invalid data')->withInput(); } } }
虽然现在功能能用了,但我还是有点搞不懂:为什么之前用普通的插入方法(比如insert)不行,必须用upsert才能成功写入?另外,在这种关联表的自动创建场景下,还有哪些需要注意的细节,能帮我避免以后再踩类似的坑吗?
内容来源于stack exchange
相关产品推荐
相关产品推荐

