Wednesday, February 3, 2010

Re: Related lists, polymorphic habtm? (fao: AD7six ;))

On Feb 3, 2:46 am, Jon Bennett <jmbenn...@gmail.com> wrote:
> Hi bakers,
>
> Been mulling this over and haven't hit on the ideal solution yet, so
> thought I'd try and put it down to get some outside ideas.
>
> I'm trying to find a flexible way to associate a record in one table
> with many other records from other tables, but contained within a
> single list. Eg, say you're building a CMS and the home page has a
> large features 'carousel', or on a product page you want a 'if you
> like this you might like' list to point people into other areas of the
> site. An item in either of those could be a Page, Event, Article,
> Post, Product - basically any type of content in your system.
>
> I'm keen to avoid having a features and feature_items table, as
>
> General things I'm after are:
>
> - store this info in a single table (composite, I think) table
> - be able to override certain fields such as name on a per list item
> basis, or use the values from the linked data
> - be able to retrieve each list in a single set of data, allowing a
> custom order to be used
> - data should be retrievable using a standard find with contain
>
> I think what I want is a habtm that can connect to multiple models
> with some additional fields in the join table, but I'm not sure that's
> feasible, but hope it is.

a join table with more than 2 fields is a model, and a model that can
link to anything is (as you know) polymorphic.

Therefore you want a join table something like this:

relations
id
model
foreign_id
url
title
related_model
related_foreign_id
related_url
related_title

which would allow you to relate anything to anything. I wouldn't use
the polymorphic behavior though. just create a method for returning
you related stuff - unless you denormalize as hinted above so you
don't even need to.

class Relation extends AppModel {
function related($model, $id) {
$return = array();
$data = $this->find('all', array('conditions' => array(
'OR' => array(
array('model' => $model, 'foreign_id' => $id),
array('related_model' => $model, 'related_foreign_id' => $id),
)
);
}
.. efficiently loop and get data if at all necessary
return $return;
}

hth,

AD

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: