Laravel 5 How to add multiple foreign key constraints to a User on creation?

时间秒杀一切 提交于 2020-02-02 12:13:13

问题


I now know that I can create a User using the haveMany relationship between a Region and User by doing this:

$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']),
]);

But what if there are multiple foreign keys, how do you create a user without making them fillable for more than 1 foreign key constraint? What if there were 3 or 4?

Example of the relationships setup in the different models:

Region hasMany Users, or
User belongsTo a Region

Location hasMany Users, or 
User belongsTo a Location

A stripped down version of my migration looks like this if it helps to understand the relationships better:

    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();
    });

Example of Region and Location Models:

/**
 * 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');
}

回答1:


I assume you have a model for Region and Location. Each of your region has an id and location has an id, then just add

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

to your User model

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

Edit: You can also do in any of your model

if ($this->create()) {
  return (new Model())->create(the params you need in another model);
}


来源:https://stackoverflow.com/questions/31419953/laravel-5-how-to-add-multiple-foreign-key-constraints-to-a-user-on-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!