草庐IT

php - laravel 一对多插入

coder 2024-01-05 原文

我有两个模型:UserRoles。我需要从相同的表单插入 User 和他的 Roles

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

它给我一个错误。

用户模型:

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

角色模型:

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

迁移:

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

我认为关系是正确的。

最佳答案

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

在保存角色之前,您需要更改您的代码以关联用户,如下所示:

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

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

编辑

此外,当未传入时,belongsTo 关系会根据关系函数的名称构建外键。由于您的方法名为 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');
}

两者都可以,但至少,如果将方法重命名为 user() 会使代码更合乎逻辑。

关于php - laravel 一对多插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35533597/

有关php - laravel 一对多插入的更多相关文章

  1. ruby - 如何在 Ruby 字符串中插入项目符号字符? - 2

    我正在尝试创建一个带有项目符号字符的Ruby1.9.3字符串。str="•"+"helloworld"但是,当我输入它时,我收到有关非ASCII字符的语法错误。我该怎么做? 最佳答案 你可以把Unicode字符放在那里。str="\u2022"+"helloworld" 关于ruby-如何在Ruby字符串中插入项目符号字符?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/1195

  2. ruby - 在 ruby​​ 中使用自动创建插入数组 - 2

    我想知道是否可以通过自动创建数组来插入数组,如果数组不存在的话,就像在PHP中一样:$toto[]='titi';如果尚未定义$toto,它将创建数组并将“titi”压入。如果已经存在,它只会推送。在Ruby中我必须这样做:toto||=[]toto.push('titi')可以一行完成吗?因为如果我有一个循环,它会测试“||=”,除了第一次:Person.all.eachdo|person|toto||=[]#with1billionofperson,thislineisuseless999999999times...toto.push(person.name)你有更好的解决方案吗?

  3. ruby-on-rails - 在方法调用中插入 Ruby? - 2

    在我的用户模型中,我有一堆属性,例如is_foos_admin和is_bars_admin,它们决定允许用户编辑哪些类型的记录。我想干掉我的编辑链接,目前看起来像这样:'edit'ifcurrent_user.is_foos_admin?%>...'edit'ifcurrent_user.is_bars_admin?%>我想做一个帮助程序,让我传入一个foo或bar并返回一个链接来编辑它,就像这样:助手可能看起来像这样(这不起作用):defedit_link_for(thing)ifcurrent_user.is_things_admin?link_to'Edit',edit_poly

  4. Ruby 将对象插入现有的已排序对象数组 - 2

    我有以下现有的Dog对象数组,它们按age属性排序:classDogattr_accessor:agedefinitialize(age)@age=ageendenddogs=[Dog.new(1),Dog.new(4),Dog.new(10)]我现在想插入一条新的狗记录,并将它放在数组中的正确位置。假设我想插入这个对象:another_dog=Dog.new(8)我想把它插入到数组中,让它成为数组中的第三项。这是一个人为的示例,旨在演示我特别想如何将一个项目插入到现有的有序数组中。我意识到我可以创建一个全新的数组并重新对所有对象进行排序,但这不是我的目标。谢谢!

  5. Ruby:如何将条件插入字符串连接 - 2

    在字符串连接中,是否可以直接在语句中包含条件?在下面的示例中,我希望仅当dear列表不为空时才连接"mydear"。dear=""string="hello"+"mydear"unlessdear.empty?+",goodmorning!"但是结果报错:undefinedmethod'+'fortrue我知道另一种方法是在这条语句之前定义一个额外的变量,但我想避免这种情况。 最佳答案 使用插值而不是连接更容易和更具可读性:dear=""string="hello#{'mydear'unlessdear.empty?},goodmo

  6. ruby-on-rails - 这个 C 和 PHP 程序员如何学习 Ruby 和 Rails? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它

  7. ruby - 如何在数组中间插入一个数组? - 2

    我有一个Ruby数组[1,4]。我想在中间插入另一个数组[2,3],这样它就变成了[1,2,3,4]。我可以使用[1,4].insert(1,[2,3]).flatten实现这一点,但是有更好的方法吗? 最佳答案 您可以通过以下方式进行。[1,4].insert(1,*[2,3])insert()方法处理多个参数。因此,您可以使用splat运算符*将数组转换为参数。 关于ruby-如何在数组中间插入一个数组?,我们在StackOverflow上找到一个类似的问题:

  8. ruby - 用 ruby​​ 将 2 个破折号插入这个字符串的最短方法是什么? - 2

    这是字符串:04046955104021109我需要这样格式化:040469551-0402-1109用ruby​​做到这一点的最短/最有效的方法是什么? 最佳答案 两个简单的插入就可以了:example_string.insert(-9,'-').insert(-5,'-')负数表示您从字符串末尾开始计数。如果您愿意,也可以从头数起:example_string.insert(9,'-').insert(14,'-') 关于ruby-用ruby​​将2个破折号插入这个字符串的最短方法是

  9. ruby-on-rails - 如何将变量值插入 ERB 模板中的 HTML 标签? - 2

    我有一个偏爱:如何将像o.office这样的值插入到属性中?value="#{o.office}"无效。 最佳答案 'type='text'/>或者你可以使用表单助手 关于ruby-on-rails-如何将变量值插入ERB模板中的HTML标签?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6172174/

  10. ruby-on-rails - Ruby on Rails PostGIS - 将多边形记录插入数据库 - 2

    我将RoR与PostGIS结合使用来存储位置数据。我正在尝试使用圆(例如,带半径的中心点)来存储估计位置。我试过类似的东西,但它不起作用:@location=Location.new(:place_id=>place.id,:circle=>%{ST_Buffer(ST_MakePoint(#{latitude},#{longitude})::geography,#{accuracy})})我也尝试过使用RGeo,它是出厂设置,但不确定如何准确使用它。任何帮助将不胜感激。谢谢。编辑1:我取得了一些进步。factory=RGeo::Cartesian.factorycenter_poin

随机推荐