On Wednesday, March 16, 2016 at 7:11:36 PM UTC-7, [email protected] wrote: > > Hi, > > I have a Label model and an Asset model with many_to_many between them, > > I can do: > > @assets = Asset.eager_graph(:labels).where(labels__name: ['foo', 'bar']) > > This will return all asset with EITHER 'foo' or 'bar' labels, but what I > want is to return the assets with BOTH labels. > > My join table just have asset_id and label_id, many_to_many in both models. > > I can come up with something too complicated to my taste using subqueries > (one subquery per label), but I wondered if sequel had a simpler way. >
In standard SQL, you would have to do multiple subqueries for this. On PostgreSQL, you could probably use array_agg and an array contains operator to do it in a single query. The other possibility is to do it in ruby: @assets = Asset.eager_graph(:labels).where(labels__name: 'foo') & Asset.eager_graph(:labels).where(labels__name: 'bar') I'm not sure either of those alternative approaches would be faster than the multiple subqueries though. Thanks, Jeremy -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/sequel-talk. For more options, visit https://groups.google.com/d/optout.
