我有一个名为“折扣”的表,其中有一个名为user_id的数组列。
create_table "discounts", force: :cascade do |t|
t.string "amount"
t.string "name"
t.string "from"
t.string "to"
t.integer "user_id", default: [], array: true我想搜索整个折扣表,只查找有user_id(current_user.id)的行。
有什么办法植入这个搜索吗?
发布于 2018-10-01 09:21:59
Discount.where(":user_id = ANY(user_id)", user_id: current_user.id)这应该是为了你。我假设user_id是postgres数据库中的数组字段。
我建议您也索引user_id以获得更好的性能。要为数组列创建索引,必须选择GiST和GIN作为策略。文档很好地涵盖了这些选项,但经过提炼的版本是,杜松子酒查找要快得多(3倍),但构建起来需要更长时间(10倍)。如果你的数据读起来比写的要多,那就去找杜松子酒吧。
您的迁移可能类似于:
create_table "discounts", force: :cascade do |t|
t.string "amount"
t.string "name"
t.string "from"
t.string "to"
t.integer "user_id", default: [], array: true
end
add_index :discounts, :user_id, using: 'gin'https://stackoverflow.com/questions/52587888
复制相似问题