On Tuesday, March 8, 2016 at 6:44:32 PM UTC-8, MATSUSHITA Kohei wrote:
>
> Hi, sequel developer. This product is very great.
>
> I have a question about the Model#association_join with 3 tables.
>
> In the following code, is there any way to retrieve created_at of Parent?
>
> ```
> Parent.first.created_at
> => 2016-03-09 09:11:25 +0900
> GrandChild.first.created_at
> => 2016-03-09 09:11:30 +0900
>
> r = Parent.association_join(:child => :grand_child).first
> r.class
> => Parent
> r.created_at
> => 2016-03-09 09:11:30 +0900 ## OMG! this is GrandChild's value
> ```
>
> I guess, this behavior is non-intuitive.
>
> Currently, I have a workaround, using Alias feature.
>
> ```
> r = Parent.select_append(Sequel.as(Sequel.qualify(:parents, :created_at), 
> :hoge)).association_join(:child => :grand_child).first
> r.created_at
> => 2016-03-09 09:11:30 +0900
> r[:hoge]
> => 2016-03-09 09:11:25 +0900 ## Great! (but cannot use #hoge ...)
> ```
>

Sequel's default selection is *, so all columns from all tables.  Due to 
how the adapters are implemented, in the case of multiple columns with the 
same name, the last entry with the name will be used.  Your options are:

1) Explicitly alias all columns:

  p = Parent.select_all(:parents).select_append(:child__name___child_name, 
:child__created_at___child_created_at, ...).association_join(:child => 
:grand_child).first
  p.created_at
  p[:grand_child_created_at]

2) Use eager_graph:

  p = Parent.eager_graph(:child=>:grand_child).all.first
  p.created_at
  p.child.grand_child.created_at

3) Use eager_graph with graph_each extension:

  p = 
Parent.eager_graph(:child=>:grand_child).extension(:graph_each).clone(:eager_graph=>nil).all.first
  p[:parent][:created_at]
  p[:grand_child][:created_at]

4) Use eager_graph with ungraphed extension:

  p = Parent.eager_graph(:child=>:grand_child).ungraphed.first
  p.created_at
  p[:grand_child_created_at]

Note that if you want to do an INNER JOIN (as association_join does) 
instead of a LEFT OUTER JOIN (as eager_graph does), you can do:

  Parent.eager_graph_with_options({:child=>:grand_child}, 
:join_type=>:inner)
  # instead of
  Parent.eager_graph(:child=>:grand_child)

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.

Reply via email to