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, line 288
def many_through_many_association_filter_expression(op, ref, obj)
  lpks = ref[:left_primary_key_columns]
  lpks = lpks.first if lpks.length == 1
  lpks = ref.qualify(model.table_name, lpks)
  edges = ref.edges
  first, rest = edges.first, edges[1..-1]
  ds = model.db[first[:table]].select(*Array(ref.qualify(first[:table], first[:right])))
  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])}
  last_alias = if rest.empty?
    first[:table]
  else
    last_join = ds.opts[:join].last
    last_join.table_alias || last_join.table
  end

  meths = if obj.is_a?(Sequel::Dataset)
    ref.qualify(obj.model.table_name, ref.right_primary_keys)
  else
    ref.right_primary_key_methods
  end

  expr = association_filter_key_expression(ref.qualify(last_alias, Array(ref.final_edge[:left])), meths, obj)
  unless expr == SQL::Constants::FALSE
    ds = ds.where(expr).exclude(SQL::BooleanExpression.from_value_pairs(ds.opts[:select].zip([]), :OR))
    expr = SQL::BooleanExpression.from_value_pairs(lpks=>ds)
    expr = add_association_filter_conditions(ref, obj, expr)
  end

  association_filter_handle_inversion(op, expr, Array(lpks))
end
one_through_many_association_filter_expression(op, ref, obj)