Saturday, December 4, 2010

trouble with self association

Situation: I need to list many books, some of which are translations
of others in the database. I'd like to note whether a book is a
translation of another or if it has one or more translations (and link
to it/them). Thus, my Book model:

public $hasMany = array(
'Review',
'Translation' => array(
'className' => 'Book',
'foreignKey' => 'translation_source_id'
)
);
public $belongsTo = array(
'Publisher',
'TranslationSource' => array(
'className' => 'Book',
'foreignKey' => 'translation_source_id'
)
);

I didn't use translation_id because a Book can have many Translations.
This way, I can keep everything within the same table. To view a
particular Book, I'm using the following:


return $this->find(
'first',
array(
'conditions' => $conditions,
'fields' => array('Book.*'),
'contain' => array(
'Publisher',
'Translation' => array(
'fields' => array(
'Translation.id',
'Translation.translation_source_id',
'Translation.title',
'Translation.slug',
'Translation.translator',
'Translation.translation_language'
)
),
'TranslationSource' => array(
'fields' => array(
'TranslationSource.id',
'TranslationSource.title',
'TranslationSource.slug'
)
),
'Review' => array(
'order' => array('Review.sort_order' => 'ASC')
),
'Image' => array('Thumbnail')
)
)
);

For a Book that is a Translation, the data includes:

[TranslationSource] => Array
(
[id] => {the id}
[title] => {the title}
[slug] => {the slug}
)

... and Translation is empty (because the original should not be
considered a translation of a translation). So far, so good. Now, for
a Book that has one or more Translations, the Translation array
correctly includes the details for each of those. However, I also get:

[TranslationSource] => Array
(
[id] =>
[title] =>
[slug] =>
[TranslationSource] => Array
(
)
)

So, my code can't simply check if $data['TranslationSource'] is empty
to decide how to proceed. And what's with the nested
TranslationSource? I figure this has to be something to do with how
I've created the associations but can't figure out where I've gone
wrong.

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: