| Module | Sequel::Plugins::DatasetAssociations::DatasetMethods |
| In: |
lib/sequel/plugins/dataset_associations.rb
|
For the association given by name, return a dataset of associated objects such that it would return the union of calling the association method on all objects returned by the current dataset.
This supports most options that are supported when eager loading. It doesn‘t support limits on the associations, or one_to_one associations that are really one_to_many and use an order to select the first matching object. In both of those cases, this will return an array of all matching objects.
# File lib/sequel/plugins/dataset_associations.rb, line 73
73: def associated(name)
74: raise Error, "unrecognized association name: #{name.inspect}" unless r = model.association_reflection(name)
75: ds = r.associated_class.dataset
76: sds = opts[:limit] ? self : unordered
77: ds = case r[:type]
78: when :many_to_one
79: ds.filter(r.qualified_primary_key=>sds.select(*Array(r[:qualified_key])))
80: when :one_to_one, :one_to_many
81: ds.filter(r.qualified_key=>sds.select(*Array(r.qualified_primary_key)))
82: when :many_to_many
83: ds.filter(r.qualified_right_primary_key=>sds.select(*Array(r.qualified_right_key)).
84: join(r[:join_table], r[:left_keys].zip(r[:left_primary_keys]), :implicit_qualifier=>model.table_name))
85: when :many_through_many
86: fre = r.reverse_edges.first
87: fe, *edges = r.edges
88: sds = sds.select(*Array(r.qualify(fre[:table], fre[:left]))).
89: join(fe[:table], Array(fe[:right]).zip(Array(fe[:left])), :implicit_qualifier=>model.table_name)
90: edges.each{|e| sds = sds.join(e[:table], Array(e[:right]).zip(Array(e[:left])))}
91: ds.filter(r.qualified_right_primary_key=>sds)
92: else
93: raise Error, "unrecognized association type for association #{name.inspect}: #{r[:type].inspect}"
94: end
95: ds = model.apply_association_dataset_opts(r, ds)
96: r[:extend].each{|m| ds.extend(m)}
97: ds
98: end