我现在知道我可以通过执行以下操作使用区域和用户之间的 haveMany 关系创建用户:
$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']),
]);
但是如果有多个外键,你如何创建一个用户而不使它们可以填充超过 1 个外键约束?如果有 3 个或 4 个呢?
不同模型中的关系设置示例:
Region hasMany Users, or
User belongsTo a Region
Location hasMany Users, or
User belongsTo a Location
如果它有助于更好地理解关系,我的迁移的精简版本如下所示:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('region_id')->unsigned();
$table->integer('location_id')->unsigned();
$table->timestamps();
$table->foreign('region_id')
->references('id')
->on('regions');
$table->foreign('location_id')
->references('id')
->on('locations');
});
Schema::create('regions', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 100);
$table->timestamps();
});
Schema::create('locations', function (Blueprint $table) {
$table->increments('id');
$table->string('street_address', 100);
$table->string('city', 50);
$table->string('province', 50);
$table->string('country', 50);
$table->string('postal_code', 10);
$table->timestamps();
});
区域和位置模型示例:
/**
* Region may have many users.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany('App\User');
}
/**
* Location may have many users.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany('App\Location');
}