我有一個陣列欄位,books 表中的 author_ids,我需要撰寫一個查詢來查找陣列資料。
有什么辦法我可以得到,即使author_ids has [1,3]它的價值,但是當我檢查時array [1,5],我仍然可以獲得資料,因為它有 1 個共同點?這里('author_ids @> ARRAY[?]::integer[]',[1,5])
where('author_ids @> ARRAY[?]::integer[]',[1,5])
這不回傳資料,where('author_ids @> ARRAY[?]::integer[]',[1,3])因為它有 [1,3]。我想獲取資料where [auther_ids] ? any [passed_aray]
uj5u.com熱心網友回復:
TL;博士
Postgres 檔案
問題
anyarray @> anyarray → 布林值
第一個陣列是否包含第二個,也就是說,出現在第二個陣列中的每個元素是否等于第一個陣列的某個元素?(重復項沒有特殊處理,因此 ARRAY[2] 和 ARRAY[1,1] 都被認為包含另一個。)
陣列[1,4,3] @> 陣列[3,1,3] → t
這意味著如果您有 [1,3,7,9] 作為 authors_ids 并且您使用 [1, 5] 查詢它不會回傳任何內容。為什么?
@> 檢查您的查詢陣列是否是列的子集,并且 [1,5] 不是 [1,3,7,9] 的子集,因為缺少 5。
解決方案
您需要的運算子是&&:
anyarray && anyarray → 布林值
陣列是否重疊,即是否有任何共同元素?
陣列[1,4,3] && 陣列[2,1] → t
使用它,您的查詢將如下所示:
where('author_ids && ARRAY[?]::integer[]',[1,5])
重構
我認為正確的做法是在您的模型上為 Author 類使用 has_many 關聯。
class CurrentModel < ApplicationRecord
has_many :authors
end
然后您的查詢將如下所示:
joins(:authors).where(authors: { id: [1,5] }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465309.html
標籤:数组 轨道上的红宝石 红宝石 ruby-on-rails-3 where子句
上一篇:在字符陣列之后獲取字串
