使用Rails中的Join 5在单个查询中删除多个表

时间:2018-09-13 16:29:14

标签: ruby-on-rails ruby-on-rails-5

这是我在rails中进行的查询,我想从feedfeed mappings表中删除与单个查询中的某些条件匹配的条目,如果我使用destroy_all,它将删除一个条目首先,它将首先删除提要,然后删除每个条目的feed_mappings,而如果我仅将结果查询上的Select语句更改为Delete feed, feed_mappings,则可以删除一个查询中的所有内容。帮助我在单个查询中解决此问题。

Feed.joins(:feed_mappings)
          .joins('inner join notifications on notifications.id = feed_mappings.source_id')
          .joins('inner join user_feedbacks on user_feedbacks.source_id = notifications.picked_for_company')
          .joins('inner join user_feedback_contexts on user_feedback_contexts.user_feedback_id = user_feedbacks.id')
          .where(user_feedbacks: {source_type: 'Company', user_id: user.id},
                 user_feedback_contexts: {context: 'block'},
                 notifications: {user_id: user.id},
                 feed_mappings: {source_type: 'Notifications::Notification'})

这会生成

SELECT `feeds`.* FROM   `feeds` 
   INNER JOIN `feed_mappings` 
           ON `feed_mappings`.`feed_id` = `feeds`.`id` 
   INNER JOIN notifications 
           ON notifications.id = feed_mappings.source_id 
   INNER JOIN user_feedbacks 
           ON user_feedbacks.source_id = notifications.picked_for_company 
   INNER JOIN user_feedback_contexts 
           ON user_feedback_contexts.user_feedback_id = user_feedbacks.id 
   WHERE  `user_feedbacks`.`source_type` = 'Company' 
   AND `user_feedbacks`.`user_id` = 6 
   AND `user_feedback_contexts`.`context` = 'block' 
   AND `notifications`.`user_id` = 6 
   AND `feed_mappings`.`source_type` = 'Notifications::Notification' 

我想要什么

DELETE `feeds`, `feed_mappings` FROM   `feeds` 
   INNER JOIN `feed_mappings` 
           ON `feed_mappings`.`feed_id` = `feeds`.`id` 
   INNER JOIN notifications 
           ON notifications.id = feed_mappings.source_id 
   INNER JOIN user_feedbacks 
           ON user_feedbacks.source_id = notifications.picked_for_company 
   INNER JOIN user_feedback_contexts 
           ON user_feedback_contexts.user_feedback_id = user_feedbacks.id 
   WHERE  `user_feedbacks`.`source_type` = 'Company' 
   AND `user_feedbacks`.`user_id` = 6 
   AND `user_feedback_contexts`.`context` = 'block' 
   AND `notifications`.`user_id` = 6 
   AND `feed_mappings`.`source_type` = 'Notifications::Notification' 

0 个答案:

没有答案