On Wednesday, April 15, 2015 at 11:23:03 AM UTC-7, Elanor Riley wrote:
>
> I have the following tables:
>
> create_table(:tours) do
> primary_key :id
> String :group_type, :null => false
>
> String :group_name
> String :group_fname, :null => false
> String :group_lname, :null => false, :index => true
> String :group_email, :null => false
> String :group_phone, :null => false
> end
>
> create_table(:guides) do
> primary_key :id
>
> String :guide_name
> String :guide_email
>
> boolean :guide_notify, :default => false
> end
>
> create_table(:tours_guides) do
> foreign_key :guide_id, :guides, key: :id
> foreign_key :tour_id, :tours, key: :id
> index [:guide_id, :tour_id], :unique => true
> end
>
> #classes.rb
>
> class Tour < Sequel::Model(:tours)
> many_to_many :guides
> end
>
> class Guide < Sequel::Model(:guides)
> many_to_many :tours
> end
>
> In plain English, a Tour can have more than one guide, and Guides can be
> assigned to many tours.
> In general, this works. I can do something like Tour[1].guides and get a
> list of guides without issue. I can also do Guide[1].tours and see the
> reciprocal.
>
> Here's what I am trying to do that is causing me trouble: I need a list of
> all tours, with the guide names grouped together in one record.
>
> # Query
> DB[:tours].left_join(:guides).select(:forms__id, :guides__guide_name).all
>
> # Result
> [{:id=>1, :guide_name=>"Elanor"}, {:id=>1, :guide_name=>"Test"}]
>
> # Expected Result
> [{:id=>1, :guide_name=>["Elanor", "Test"]}]
>
> If it helps, I'm trying to get this in one query with the guide names
> nested with their tours so its easy to convert the whole shebang to JSON.
>
With PostgreSQL, this should be fairly easy using array_agg:
DB[:tours].left_join(:tour_guides, :tour_id=>:id).
left_join(:guides, :id=>:guide_id).
select_group(:tours__id).
select_append{array_agg(:guides__guide_name).as(:guide_name)}
If you are unfortunate enough to be using something else, you could try
Dataset#to_hash_groups, but that will give you a slightly different result:
DB[:tours].left_join(:tour_guides, :tour_id=>:id).
left_join(:guides, :id=>:guide_id).
select_hash_groups(:tours__id, :guides__guide_name)
# => {1=>["Elanor", "Test"]}
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 http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.