[英]updating in batch one to many relationship rails 2.3.5 one sql statement?
Lets say user has many accounts, so user_id is on accounts table. 假设用户有多个帐户,因此user_id在帐户表中。 If I want to update all the users accounts and give them to another user in 1 sql call is there a "rails" way to do this?
如果我想更新所有用户帐户,并在1个sql调用中将它们分配给另一个用户,是否有“方法”来做到这一点? (without doing executeSQL)
(不执行executeSQL)
So Joel has 1000 accounts, Fred has no accounts, Joel wants to give Fred all his accounts, normally I could iterate through joels accounts and assign them to fred user, but that would result in 1000 sql calls.. 因此Joel有1000个帐户,Fred没有帐户,Joel希望将Fred的所有帐户提供给我,通常我可以遍历joels帐户并将其分配给fred用户,但这将导致1000次sql调用。
fred.accounts += joel.accounts
This will immediately move all accounts from joel
and add them to any existing accounts that fred
has. 这将立即将所有帐户从
joel
移出,并将它们添加到fred
拥有的任何现有帐户中。 By "immediate" I mean the SQL will execute the update right away - you don't need to additionally save the records that are being moved. “立即”是指SQL立即执行更新-您无需另外保存要移动的记录。
If fred
has no accounts, that's fine too, it still works the same - it will simply add joel
's accounts to fred
's empty list of accounts. 如果
fred
没有帐户,那也很好,它仍然可以正常工作-它将joel
的帐户简单地添加到fred
的空帐户列表中。
This works with both "one-to-many" and "many-to-many" relationship. 这适用于“一对多”和“多对多”关系。
In the one-to-many situation, it does this my changing the user_id
field on the accounts
table for all accounts previously owned by joel
. 在一对多情况下,我通过更改
joel
先前拥有的所有帐户的accounts
表上的user_id
字段来执行此操作。
In the many-to-many situation (where accounts can be co-owned by multiple users), it appears to simply change the user_id
field on the join table (presumably called accounts_users
) for all accounts that joel
co-owns with zero or more other users. 在许多一对多的情况(其中账户可以由多个用户共同拥有),这似乎只是改变
user_id
上连接表(大概叫场accounts_users
)为所有帐户joel
与零个或多个共同拥有其他用户。 This effectively replaces any accounts that joel
co-owned with fred
. 这实际上将取代
joel
与fred
共同拥有的任何帐户。 All other co-owners on the account are unaffected, it seems. 帐户上的所有其他共同所有者似乎都没有受到影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.