【问题标题】:How to insert multiple rows in pivot table using Eloquent?如何使用 Eloquent 在数据透视表中插入多行?
【发布时间】:2020-01-25 00:04:28
【问题描述】:

我有一个名为user_machine_pivot 的数据透视表,它连接两个表:usermachines,在创建新用户时,我从下拉列表中选择他可以操作的机器。我想要实现的是,当我发出axios.post 请求时,我想使用user_idmachine_id 在数据透视表中插入多行。这是我的用户模型代码:

public function machine()
{
    return $this->belongsToMany(Machine::class, 'user_machine_pivot')->withTimestamps();
}

我的axios.post 从 Telescope 请求内容: {

full_name: "RandomName",
username: "RandomName",
password: "********",
machines: [
3,
2
]
}

我的用户控制器:

$user = User::create($validatedUserData);
$user->machine()->attach($user->id, ['machine_id' => $machines]);

首先,我正在验证 UserData 并创建一个用户,然后我尝试将用户附加到数据透视表中的机器上。 任何帮助和指点表示赞赏。

【问题讨论】:

    标签: laravel eloquent pivot-table


    【解决方案1】:
    $user->machine()->attach($user->id, ['machine_id' => $machines]);
    

    这是不对的。你已经有$user,并且你想附加一个特定的machine,所以你需要将该id传递给machines()->attach()

    $user = User::create($validatedUserData);
    $machine = ...; 
    // Not sure how you're getting `$machines`, and it should be singular `$machine`
    
    $user->machines()->attach($machine->id, [...]);
    // Replace `[...]` with any additional columns.
    

    注意,如果要附加多个,请使用attach()sync()

    $user->machines()->attach($machines);
    $user->machines()->sync($machines); 
    

    attach() 最好在您附加现有记录时使用,因为 sync()detach() 然后 attach() ids 您正在传递。此外,如果您需要其他列,请将您的 $machines 调整为关联数组:

    $machines = [
      1,
      2 => ["additional" => "column"],
      3
    ]; // Etc. etc.
    

    【讨论】:

    • 谢谢您的详尽回答,先生!
    • 没问题!乐于助人!
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多