php - Laravel 4 - 将多个值插入数据透视表

标签 php mysql laravel-4 pivot-table

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

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

例如

帐户:

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
}

最佳答案

你快到了!

$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

关于php - Laravel 4 - 将多个值插入数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989145/

相关文章:

php - 爬虫从url添加参数到链接

laravel-4 - 调用未定义的方法 Illuminate\Database\Query\Builder::save()?

php - 默认包含的 Blade 模板产量

mysql - 从 Laravel 4 中标题为 lorem ipsum 的数据库中选择所有数据

php - 导入Excel文件到MySQL

php - 在像 Facebook 这样的 jomsocial 墙中添加 href

php - 无法从 php 脚本获取记录到 android 应用程序

php - 拉维和 PHP : Return special formatted JSON

php - 如果数据库中没有记录,则分页错误

javascript - 如何通过javascript将网站代码包含到iframe中?