2

我现在知道我可以通过执行以下操作使用区域和用户之间的 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');
}
4

1 回答 1

1

我假设您有一个区域和位置模型。您的每个地区都有一个 id,位置有一个 id,然后只需添加

$this->hasMany('where your Region model is', 'region_id', 'id');
$this->hasMany('where your Location model is', 'location_id', 'id');

到您的用户模型

参考: http: //laravel.com/docs/5.0/eloquent#one-to-many

编辑:你也可以在你的任何模型中做

if ($this->create()) {
  return (new Model())->create(the params you need in another model);
}
于 2015-07-15T01:32:55.673 回答