Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel one to many inserting

I have two models: User and Roles. I need to insert User and his Roles from same form.

$user = new User;
$user ->name = $request ->input('name');
$user ->email = $request ->input ('email');
$user -> password = $request ->input ('pass');
$user ->save();
$role = new Role;
$role ->name = $request ->input('role');
$role ->explain = $request ->input('exp');
$role ->save();
$role ->roles() ->save($user);

It gives me an error.

User model:

public function roles()
{
    # code...
    return $this ->hasMany('App\Role');
}

Role model:

public function users()
{
    # code...
    return $this ->belongsTo('App\User');
}

migrations:

   Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->index();
        $table->text('name');
        $table->string('explain');
        $table->timestamps();
        //cascade
        $table->foreign('user_id')->references('id')->on('users')-    >onDelete('cascade');
    });

I think that is the relationship is done correctly.

like image 691
user5565240 Avatar asked Feb 21 '16 07:02

user5565240


2 Answers

Your issue is that you saved your Role before you associated it with a user. Since you didn't associate it to a user, your roles.user_id field is empty, and that violates your foreign key.

You need to change your code to associate the user before saving the role, as shown below:

// create the user
$user = new User;
$user->name = $request->input('name');
$user->email = $request->input ('email');
$user->password = $request->input ('pass');
$user->save();

$role = new Role;
$role->name = $request->input('role');
$role->explain = $request->input('exp');

// option 1:
// this will set the user_id on the role, and then save the role to the db
$user->roles()->save($role);

// option 2:
// associate the user to the role (sets the user_id field)
// then you need to save your role
$role->users()->associate($user);
$role->save();

Use option 1 or option 2, not both.

Edit

Additionally, when not passed in, the belongsTo relationship builds the foreign key based on the name of the relationship function. Since your method is named users, it is going to look for the users_id field, which is not correct. You will either need to pass in the correct foreign key name as the second parameter, or rename your relationship method from users() to user().

// option 1
// pass in the foreign key field as the second parameter
public function users()
{
    return $this->belongsTo('App\User', 'user_id');
}

// option 2
// rename the relationship to user
public function user()
{
    return $this->belongsTo('App\User');
}

You can do both, but at the least, it would make the code more logical if you were to rename the method to user().

like image 169
patricus Avatar answered Nov 11 '22 10:11

patricus


this error because you didn't pass the user_id for the roles tables. it is a foreign key in this table and must be passed. you can save your one to many relation tables in this way:

https://laravel.com/docs/4.2/eloquent#inserting-related-models

firstly you save the master table user row, then by find() method you can save all details rows in roles table like the link example.

$role = new Role(array('','','','')); // array of roles row values you want save
$user = User::find(1); // where 1 is id
$role = $user->roles()->save($role );
like image 3
Gouda Elalfy Avatar answered Nov 11 '22 10:11

Gouda Elalfy