我有一个用户表和一个帐户表。
此帐户表定义用户可以拥有哪些帐户。
例如
帐户:
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/