HABTM finds with “AND” joins, NOT “OR”

前端 未结 1 358
清歌不尽
清歌不尽 2021-02-06 18:02

I have two models, associated with a HABTM (actually using has_many :through on both ends, along with a join table). I need to retrieve all ModelAs that is associated with BOTH

1条回答
  •  花落未央
    2021-02-06 18:50

    You may do this:

    1. build a query from your ModelA, joining ModelB (through the join model), filtering the ModelBs that have one of the values that you are looking for, that is putting them in OR (i.e. where ModelB = 'ModelB_1' or ModelB = 'ModelB_2'). With this query the result set will have multiple 'ModelA' rows, exactly one row for each ModelB condition satisfied.

    2. add a group by condition to the query on the ModelA columns you need (even all of them if you wish). The count() for each row is equal to the number of ModelB conditions satisfied*.

    3. add a 'having' condition selecting only the rows whose count(*) is equal to the number of ModelB conditions you need to have satisfied

    example:

    model_bs_to_find = [100, 200]
    ModelA.all( :joins=>{:model_a_to_b=>:model_bs}, 
                :group=>"model_as.id", 
                :select=>"model_as.*",
                :conditions=>["model_bs.id in (?)", model_bs_to_find], 
                :having=>"count(*)=#{model_bs_to_find.size}")
    

    N.B. the group and select parameters specified in that way will work in MySQL, the standard SQL way to do so would be to put the whole list of model_as columns in both the group and select parameters.

    0 讨论(0)
提交回复
热议问题