Laravel 5.x 如何创建具有外键约束的新用户?

Laravel 5.x How do you create a new user that has a foreign key constraint?

我可以使用以下方式创建新用户:

User::create([
    'username' => $data[ 'username' ],
    'email' => $data[ 'email' ],
    'first_name' => $data[ 'first_name' ],
    'last_name' => $data[ 'last_name' ],
    'password' => bcrypt($data[ 'password' ]),
]);

但现在我想创建一个现在具有 region_id 约束的用户,所以我认为可以通过将 region_id 添加到 fillable 并将其添加到用户创建来实现:

User::create([
    'region_id' => $data[ 'region_id'
    'username' => $data[ 'username' ],
    'email' => $data[ 'email' ],
    'first_name' => $data[ 'first_name' ],
    'last_name' => $data[ 'last_name' ],
    'password' => bcrypt($data[ 'password' ]),
]);

在我的迁移中,我添加了:

$table->integer('region_id')->unsigned();

$table->foreign('region_id')
      ->references('id')
      ->on('regions');

并通过分配 region_id 使用工厂为它播种,但现在在应用程序中注册失败并抛出:

Undefined index: region_id

我再次查看了文档,发现我可以在该字段上为迁移添加索引,但经过更多阅读后,似乎 MySQL 实际上可能会自动索引外键。

  1. 验证 $data 数组包含 region_id
  2. 不要在可填写字段中添加 region_id,而是这样做:

    $region = Region::find($data['region_id']);
    
    $region->users()->create([
       'username' => $data['username'],
       'email' => $data['email'],
       'first_name' => $data['first_name'],
       'last_name' => $data['last_name'],
       'password' => bcrypt($data['password']),
    ]);
    

    这将在用户对象中自动添加 region_id 字段。

Note: Make sure you have region hasMany users relationship in region model.