1

我正在使用Sequel gem 批量更新 MySql 中的用户。

users = Users.filter(:id => ids).all
raise if users.nil?

updated_users = Users.filter(:id => addon_ids).update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => 3

根据Sequel 文档

“更新 [和删除] 应该返回受影响的行数......”

所以上面的行为是预期的,但我的问题是,我怎样才能让 Sequel gem 返回更新的记录而不是受影响的记录数?

我期待这种行为:

users = Users.filter(:id => ids).all
raise if users.nil?

updated_users = Users.filter(:id => addon_ids).update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => [#<Users @values={:id=>1, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>2, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>3, :moderator_id=>"testuser", :deleted=>1}>]
4

2 回答 2

0

好吧,这就是 DB 返回的结果,因此 Sequel 会按照开发人员的预期进行。而是这样做:

users = Users.where(:id => ids)
raise if users.empty?

updated_users = Users.where(:id => addon_ids)
updated_users.update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => [#<Users @values={:id=>1, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>2, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>3, :moderator_id=>"testuser", :deleted=>1}>]

这样您就不会将受影响的行数分配给updated_users.

于 2017-10-14T06:18:43.163 回答
0

对于可能仍在寻找这个的人,根据您的数据库引擎,您可以使用returning.

updated_users = Users.returning.filter(:id => addon_ids).update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => [#<Users @values={:id=>1, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>2, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>3, :moderator_id=>"testuser", :deleted=>1}>]

文档:http ://www.rubydoc.info/github/jeremyevans/sequel/Sequel%2FDataset%3Areturning

于 2018-02-13T08:52:01.883 回答