I'm having some trouble with a HABTM association.
What I'm trying to do is the following:
Template HABTM Medium Pages HABTM Medium
To do this I created the join table object_media
and wanted it to have object_id
, medium_id
and model
fields. the page id or template id would go into the object_id
field and the model would have either 'Page' or 'Template'. By doing this I would be able to connect any model with my Medium model. (Medium = media, all images, videos, documents, etc get saved there). Then I can just pass conditions into the HABTM relation to get only media for that specific model. eg: ObjectMedium.model => 'Template'
would return all media connected to template.
In short: I want 1 table that links any model to any medium.
Template.php
class Template extends AppModel{
public $name = 'Template';
public $hasMany = array(
'TemplateColumn'
);
public $hasAndBelongsToMany = array(
'Medium' => array(
'className' => 'Medium',
'joinTable' => 'object_media',
'foreignKey' => 'object_id',
'associationForeignKey' => 'medium_id'
)
);
}
Medium.php
class Medium extends AppModel{
public $name = 'Medium';
public $useTable = 'media';
public $hasAndBelongsToMany = array(
'Template' => array(
'className' => 'Template',
'joinTable' => 'object_media',
'foreignKey' => 'medium_id',
'associationForeignKey' => 'object_id'
)
);
}
However, feeding it the following data wouldn't even save the medium:
Array
(
[Template] => Array
(
[name] =>
)
[TemplateColumn] => Array
(
[0] => Array
(
[block] => 0
[column] => 0
[grid] => 7
)
[1] => Array
(
[block] => 0
[column] => 1
[grid] => 5
)
[2] => Array
(
[block] => 1
[column] => 0
[grid] => 6
)
[3] => Array
(
[block] => 1
[column] => 1
[grid] => 6
)
)
[Medium] => Array
(
[0] => Array
(
[name] => 7917196b42c3626c10ab024bbafb8171
[src] => 134a16c2202ff2b0c9b1c51dddb1bcfc.jpg
[type] => Image
)
)
This gives me the following queries:
INSERT INTO `templates` (`name`, `modified`, `created`) VALUES ('', '2011-11-20 15:18:46', '2011-11-20 15:18:46')
SELECT `ObjectMedium`.`medium_id` FROM `object_media` AS `ObjectMedium` WHERE `ObjectMedium`.`object_id` = 30
INSERT INTO `template_columns` (`block`, `column`, `grid`, `template_id`, `modified`, `created`) VALUES (0, 0, 7, 30, '2011-11-20 15:18:46', '2011-11-20 15:18:46')
INSERT INTO `template_columns` (`block`, `column`, `grid`, `template_id`, `modified`, `created`) VALUES (0, 1, 5, 30, '2011-11-20 15:18:46', '2011-11-20 15:18:46')
INSERT INTO `template_columns` (`block`, `column`, `grid`, `template_id`, `modified`, `created`) VALUES (1, 0, 6, 30, '2011-11-20 15:18:46', '2011-11-20 15:18:46')
INSERT INTO `template_columns` (`block`, `column`, `grid`, `template_id`, `modified`, `created`) VALUES (1, 1, 6, 30, '2011-11-20 15:18:46', '2011-11-20 15:18:46')
Any Ideas of what is going wrong? And how to add the model name in the join table?