英文:
Laravel: how to store same relation but with different additional column
问题
我有的表格:
用户表:id,姓名。
角色表:id,姓名。
用户角色关联表:用户id,角色id,公司id。
主要思想是用户可以在不同公司拥有相同的角色。例如:
用户id | 角色id | 公司id
______________________________
1 | 1 | 1
1 | 1 | 2
当我尝试执行sync()
时,它只存储一行,而不是两行,因为在这两种情况下用户id
和角色id
相同。找不到解决办法,也许是我没有提供正确的句子来进行搜索
英文:
tables that I have:
users: id, name.
roles: id, name.
role_user: user_id, role_id, company_id.
the main idea is that user can have same roles but in different companies.
for example:
user_id | role_id | company_id
______________________________
1 | 1 | 1
1 | 1 | 2
when I try sync()
, it stores only one row instead of two, because of user_id
and role_id
in both cases are same.
couldn't find solution, maybe it's my bad that I couldn't provide correct sentence to search
答案1
得分: 1
你的主要问题是当你尝试对其他公司进行sync()
时,它会移除另一个
你可以尝试这个
$user = User::find($user_id);
// 同步特定的 company_id
$user->roles()->sync([$role_id => ['company_id' => $company_id]]);
sync()
方法默认同步在你的情况下的 2 个主要键是 user_id
和 role_id
,但如果你需要同步更多的内容,你需要将其作为括号中的参数添加进去
这是你情况下的相同示例:
同步关联列
英文:
your main problem is when you try to sync()
for other company it's remove the other one
you can try this
$user = User::find($user_id);
// sync a specific company_id
$user->roles()->sync([$role_id => ['company_id' => $company_id]]);
the sync()
method by default syncing the 2 main keys in your situation is user_id
& role_id
, But if you need to sync more than that you need to add it as a parameter in brackets
here same example for your case :
sync paivot columns
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论