[Dbix-class] LEFT JOIN with an "OR"

J. Shirley jshirley at gmail.com
Tue Jun 10 00:22:46 BST 2008


I have finally found a query that doesn't involve subselects that I
can't sort out how to get into DBIC.  There will be much celebration
after I figure this out.

The structure of these tables is a bit odd, so bear with me.

A Thread has_many discussable_threads
A discussable_thread belongs to a 'discussable'

A 'discussable' has a descriptor as to what is being discussed (like "Topic")

The Thread class can have children, using
DBIx::Class::Tree::AdjacencyList - now, for various reasons the
_children_ of a Thread do not get a link to a discussable.  So, if you
have $thread with children, then
$thread->children->first->discussable_threads->count == 0

Hope that makes sense, and I'm happy to clarify.  Now, the problem
comes in that I need to do a LEFT JOIN to infer if the thread or an
immediate child is linked to a discussable with a certain topic.  This
is easily accomplished with an "OR" condition in the LEFT JOIN on the
connection to discussable_threads.  Easily in SQL, but I'm completely
stumped on DBIC.  To get an idea of how that works, here is the query
that works the way we want:

SELECT
   `me`.pk1, `me`.name, `me`.dt_created,     `discussable`.*
FROM
   `threads` `me`
LEFT JOIN `discussable_threads` `discussable_threads` ON
     ( ( `discussable_threads`.`thread_pk1` = `me`.`parent_pk1` ) OR (
`discussable_threads`.`thread_pk1` = `me`.`pk1` ) )
LEFT JOIN `discussables` `discussable` ON ( `discussable`.`pk1` =
`discussable_threads`.`discussable_pk1` )
LEFT JOIN `topics` `topics` ON ( `topics`.`discussable_pk1` =
`discussable`.`pk1` );

Now, at this point I would ideally have an $rs I can chain off of to
do filtering according to these rules.

So, if DBIC can do this I'd love to hear about it and will cook up
something for the cookbook.  If it can't, suggestions on a patch would
be welcome but I think the best case would be an arbitrary SQL result
source that includes these columns may be the only (immediate) path
forward?

Thanks,
-J



More information about the DBIx-Class mailing list