代码之家  ›  专栏  ›  技术社区  ›  Ilja KO

如何在数据库中搜索保存在jointable中的特定m到n关系

  •  0
  • Ilja KO  · 技术社区  · 6 年前

    我正在Rails应用程序上使用postgreSQL数据库。我已经建立了 Slots Hashtags 插槽 谁匹配特定 标签 url params

      create_table "hashtags", force: :cascade do |t|
        t.string "value"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
      end
    
      create_table "hashtags_slots", id: false, force: :cascade do |t|
        t.bigint "hashtag_id", null: false
        t.bigint "slot_id", null: false
        t.index ["hashtag_id"], name: "index_hashtags_slots_on_hashtag_id"
        t.index ["slot_id"], name: "index_hashtags_slots_on_slot_id"
      end
    
      create_table "slots", force: :cascade do |t|
        t.string "slot_name"
        t.string "file_path"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.index ["slot_name"], name: "index_slots_on_slot_name"
      end
    

    我想显示填充了 slots 谁拥有通过 params[:hashtags] . Hashtags的值可以包含一个或多个字符串,如下所示:

    hashtags = "NetEnt PlayNGo Novomatic"
    

    这是在房间里 index 政府的行动 Slot 控制器

    if(params[:slot_name])
          @slots = Slot.where(slot_name: params[:slot_name]).paginate(page: params[:page])
        elsif(params[:hashtags])
          @slots = slotsWithAtLeastOneOfThose(params[:hashtags])
        else
          @slots = Slot.all.paginate(page: params[:page])
        end
    

    一个方法应该怎么做

    slotsWithAtLeastOneOfThose(hashtags)
      slots = ...
      return slots
    end
    

    插槽 hashtag hashtags 变量

    考虑这些关系:

    :

     id: 1 slot_name: Book of Dead
     id: 2 slot_name: Big Win Cat
     id: 3 slot_name: Big Bad Wolf
    

    标签表:

     id: 1 value: PlayNGo
     id: 2 value: Fun
     id: 3 value: NetEnt
     id: 4 value: MicroGaming
     id: 5 value: NotFun
    

    Hashtags\u Slots表 看起来像这样:

    slot_id            hashtag_id
    1                  1
    1                  2
    2                  2
    2                  3
    2                  5
    3                  4
    3                  5
    

    现在是方法

    slotsWithAtLeastOneOfThose("PlayNGo NetEnt")
    

    应该给我所有的 使用标签 PlayNGo NetEnt

    在这种情况下

     id: 1 slot_name: Book of Dead
     id: 2 slot_name: Big Win Cat
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Vishal    6 年前

    请检查下面的查询以获取具有特定哈希标记值的插槽

    if(params[:slot_name])
       @slots = Slot.where(slot_name: params[:slot_name]).paginate(page: params[:page])
    elsif(params[:hashtags])
       @slots = Slot.joins(:hashtags).where("hashtags.value LIKE ?", "%#{params[:hashtags]}%")
    else
       @slots = Slot.all.paginate(page: params[:page])
    end