laravel 一对多插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35533597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:16:37  来源:igfitidea点击:

laravel one to many inserting

phplaravelone-to-many

提问by user5565240

I have two models ,user & 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 give 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

我认为这是关系做得正确

回答by patricus

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

您的问题是您Role在将其与用户关联之前保存了您的信息。由于您没有将其与用户相关联,因此您的roles.user_id字段为空,这违反了您的外键。

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.

使用选项 1 或选项 2,不要同时使用。

Edit

编辑

Additionally, when not passed in, the belongsTorelationship 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_idfield, 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().

此外,当未传入时,belongsTo关系会根据关系函数的名称构建外键。由于您的方法名为 named users,它将查找users_id不正确的字段。您需要将正确的外键名称作为第二个参数传递,或者将您的关系方法重命名users()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().

您可以同时执行这两种操作,但至少,如果您将方法重命名为user().

回答by Gouda Elalfy

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:

此错误是因为您没有为角色表传递 user_id。它是该表中的外键,必须传递。您可以通过这种方式保存一对多关系表:

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

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

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

首先您保存主表用户行,然后通过find()方法您可以像链接示例一样保存角色表中的所有详细信息行。

$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 );