简体   繁体   English

如何在原始查询(rails + postgres)中使用动态 id 数组?

[英]How to use dynamic array of ids in raw query (rails + postgres)?

I have this code我有这个代码

Language.all.map{|l|[l.language, l.accounts.joins(:children).where("accounts.id IN (?)", @accounts.ids).uniq.count]}

I am trying to get this as output我正在尝试将其作为输出

[["eng", 5] ["span", 3] ["ital", 4] ... ]

I want to write it as a raw query.我想把它写成原始查询。

I tried this,我试过这个,

ActiveRecord::Base.connection.execute("select languages.language, (SELECT COUNT(*) FROM accounts where accounts.language_id = languages.id) from languages").values

but i need to pass accounts.ids dynamic.. like this但我需要通过 accounts.ids 动态..像这样

select languages.language, (SELECT COUNT(*) FROM accounts where accounts.language_id = languages.id AND (accounts.id IN (#{@accounts.ids})) from languages"

when i tried to pass accounts.id IN #{@accounts.ids} i am getting error (accounts.id IN ([2839, 284.. .. this should have been IN (2839, 284..) instead, it is taking array.当我尝试传递accounts.id IN #{@accounts.ids}时出现错误(accounts.id IN ([2839, 284.. .. 这应该是IN (2839, 284..)相反,它是采取阵列。

How to pass it dynamically?如何动态传递?

You can try:你可以试试:

"... accounts.id IN (#{@accounts.ids.join(',')})"

Hope it helps.希望能帮助到你。

You can use where(id: @accounts.ids) or where("account.ids": @accounts.ids) or where("account.ids IN?, @accounts.ids) . I believe ActiveRecord should understand all of them.您可以使用where(id: @accounts.ids)where("account.ids": @accounts.ids)where("account.ids IN?, @accounts.ids) 。我相信 ActiveRecord 应该理解所有这些.

The above 2 answers won't work if you are attempting to use an array of strings in a raw sql query.如果您尝试在原始 sql 查询中使用字符串数组,则上述 2 个答案将不起作用。 For a raw sql statement, you can use ActiveRecord's sanitize_sql_array method.对于原始 sql 语句,您可以使用 ActiveRecord 的sanitize_sql_array方法。

languages = ['eng', 'span', 'chin', 'ital']
base_query = "SELECT * FROM languages WHERE id IN (?)"
sanitized_query = ActiveRecord::Base.send :sanitize_sql_array, [base_query, languages]
ActiveRecord::Base.connection.execute(sanitized_query)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM