1

我有一个这样的 sql 查询:-

SELECT * FROM `permissions` join entities where NOT EXISTS (select
 entity_id,permission_id from role_permissions where role_id=5 and 
 entities.id = role_permissions.entity_id and permissions.id = 
 role_permissions.permission_id)

我想获得相应的 rails 查询。

我试过这个。

Permission.joins("join entities").joins("LEFT OUTER JOIN role_permissions on 
 permission_id != permissions.id  and entities.id != entity_id and 
 role_permissions.role_id= role_id").select("role_permissions.entity_id,role_permissions.role_id,
 role_permissions.permission_id").group('role_permissions.entity_id,
 role_permissions.permission_id')

但它不起作用。

谢谢哈里

4

3 回答 3

1

我最近特别喜欢 EXISTS 查询,正是因为它不需要您完全连接另一个表。据我所知,您确实必须显式编写 SQL 子句,但您仍然可以使其与 Activerecord 一起使用。您甚至可以将其放在 lambda 块内的范围内。

Permission.joins(:entities).where(<<-SQL
  NOT EXISTS(
    select
      * from role_permissions where role_id=#{your_role_id} and 
      entities.id = role_permissions.entity_id 
      and permissions.id = role_permissions.permission_id
  )
  SQL
)
于 2014-08-14T18:48:24.967 回答
0

Try this UPDATED BASED ON FIRST COMMENT

Permission.joins(:entities).joins("LEFT OUTER JOIN role_permissions on 
  permission_id != permissions.id  and entities.id != entity_id and 
  role_permissions.role_id= role_id")
  .select("role_permissions.entity_id,role_permissions.role_id,
   role_permissions.permission_id")
  .group('role_permissions.entity_id, role_permissions.permission_id')
于 2013-09-23T05:10:32.890 回答
0

尝试这样的默认 SQL 查询:

sql = "SELECT some_field FROM `permissions` join entities where NOT EXISTS (select entity_id,permission_id from role_permissions where role_id=5 and entities.id = role_permissions.entity_id and permissions.id = role_permissions.permission_id)"
results = ActiveRecord::Base.connection.execute(sql)
results.each do |result|
    @register_users << { some_field: result[0] }
end
于 2013-09-23T05:35:04.173 回答