module Sequel::Plugins::ManyThroughMany::DatasetMethods

Private Instance Methods

many_through_many_association_filter_expression(op, ref, obj) click to toggle source

Use a subquery to filter rows to those related to the given associated object

    # File lib/sequel/plugins/many_through_many.rb
403 def many_through_many_association_filter_expression(op, ref, obj)
404   lpks = ref[:left_primary_key_columns]
405   lpks = lpks.first if lpks.length == 1
406   lpks = ref.qualify(model.table_name, lpks)
407   edges = ref.edges
408   first, rest = edges.first, edges[1..-1]
409   ds = model.db[first[:table]].select(*Array(ref.qualify(first[:table], first[:right])))
410   rest.each{|e| ds = ds.join(e[:table], e.fetch(:only_conditions, (Array(e[:right]).zip(Array(e[:left])) + e[:conditions])), :table_alias=>ds.unused_table_alias(e[:table]), :qualify=>:deep, &e[:block])}
411   last_alias = if rest.empty?
412     first[:table]
413   else
414     last_join = ds.opts[:join].last
415     last_join.table_alias || last_join.table
416   end
417 
418   meths = if obj.is_a?(Sequel::Dataset)
419     ref.qualify(obj.model.table_name, ref.right_primary_keys)
420   else
421     ref.right_primary_key_methods
422   end
423 
424   expr = association_filter_key_expression(ref.qualify(last_alias, Array(ref.final_edge[:left])), meths, obj)
425   unless expr == SQL::Constants::FALSE
426     ds = ds.where(expr).exclude(SQL::BooleanExpression.from_value_pairs(ds.opts[:select].zip([]), :OR))
427     expr = SQL::BooleanExpression.from_value_pairs(lpks=>ds)
428     expr = add_association_filter_conditions(ref, obj, expr)
429   end
430 
431   association_filter_handle_inversion(op, expr, Array(lpks))
432 end
one_through_many_association_filter_expression(op, ref, obj)