Thanks for the reply. A different but related question. If I wanted to
do this without using Sequel's DSL, but instead raw SQL, what's the
best way to integrate this into the existing model.
To give an example, let's say my Post model looked like this...
class Post < Sequel::Model
one_to_many :comment
one_to_many :postmeta
def self.blogs
# ...
end
end
Where inside self.blogs, is a raw SQL query. What's generally the best
way to run and return that raw sequel query from within the context of
the model. Is a DB.run("SELECT * FROM post ...") the only real option,
or is there something else I can do? I guess ideally, it would be good
to get the database object not from the constant 'DB', but from the
model itself. Is that possible?
I've decided that I want to use raw SQL for any tricky SQL statements
(those involving multiple joins, sub-queries, etc), so I'm just trying
to find the best way to do put raw SQL into an existing model.
On Nov 13, 4:46 pm, Jeremy Evans <[email protected]> wrote:
> On Nov 12, 3:21 am, Wardrop <[email protected]> wrote:
>
>
>
> > Here's the scenario. I have a 'post' table (I've chosen not to use
> > pluralization), and a 'postmeta' table. The 'post' table stores the
> > main post information, such as title, body and date_created. The
> > 'postmeta' table stores metadata associated with the post, such as
> > tags, and the post type (e.g. whether the post is an article or a blog
> > entry).
>
> > I've created models for both the post and postmeta tables, like so...
>
> > class Postmeta < Sequel::Model
> > many_to_one :post
> > end
>
> > class Post < Sequel::Model
> > one_to_many :postmeta
> > end
>
> > The association works fine, I can assure you. My problem is, I can't
> > for the life of me, work out how to select all posts with the 'type'
> > of 'blog'. Of course, the 'type' information is stored in the
> > 'postmeta' table, so here's how I'd write that in pure SQL...
>
> > SELECT * FROM post
> > JOIN postmeta ON postmeta.post_id = post.id
> > WHERE postmeta.name = 'type' AND postmeta.value = 'blog'
>
> This query would not be generated by any association code, since it is
> not specific to a particular post or postmeta.
>
> To do filtering on associations, you can use :conditions (or a block).
>
> Post.one_to_many :postmeta, :conditions=>{:name=>'type', :value =>
> 'blog'}
>
> My guess is you really want this to be a dataset method on Post:
>
> Post.def_dataset_method(:blogs) do
> join(:postmeta, :post_id=>:id).
> filter(:postmeta__name=>'type',
> :postmeta__value=>'blog')
> end
>
> This would allow you to do this to get all posts that are blogs:
>
> Post.blogs
>
> Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sequel-talk?hl=en.