【问题标题】:Laravel 4 - Inserting multiple values into a pivot tableLaravel 4 - 将多个值插入数据透视表
【发布时间】:2015-05-01 14:50:08
【问题描述】:

我有一个用户表和一个帐户表。

此帐户表定义用户可以拥有哪些帐户。

例如

帐户:

id| name

1 | library
2 | school
3 | maths

用户:

id| username

1 | username1
2 | username2

我现在有另一个表:users_accounts

user_id | account_id

我正在为要创建的新用户创建一个界面。在这个页面上,我有基本的详细信息,还有一个复选框列表(从帐户表创建)。复选框代表用户需要为其设置的帐户。

我想做的是在创建帐户时:

$user = User::create($input);

我还想将用户 ID 和他们需要设置的帐户添加到 users_accounts 表中。一个用户可能需要多个帐户。

我可以使用数据透视表和 belongsToMany 做到这一点吗?

长期而言:

$user = User::create($input);

loop through the checkboxes {
    add a new row into the user_accounts table with the ticked checkboxes
}

【问题讨论】:

    标签: php mysql laravel-4 pivot-table


    【解决方案1】:

    你快到了!

    $user = User::create($input);
    
    $userAccounts = array();
    foreach ($checkboxes as $accountId) {
        $userAccounts[] = new UserAccount(['account_id' => $accountId]);
    }
    $user->accounts()->saveMany($userAccounts);
    

    文档: http://laravel.com/docs/5.0/eloquent#inserting-related-models

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2023-03-07
      • 2014-07-11
      • 1970-01-01
      相关资源
      最近更新 更多