2011-11-20 72 views
0

我在HABTM關聯中遇到了一些麻煩。HABTM加入表中的其他字段

我試圖做的是以下幾點:

模板HABTM中 頁面HABTM中

要做到這一點,我創建了連接表object_media,並希望它有object_idmedium_idmodel領域。頁面ID或模板ID將進入object_id字段,模型將具有「頁面」或「模板」。通過這樣做,我可以將任何模型與我的中型模型連接起來。 (媒體=媒體,所有圖像,視頻,文件等保存在那裏)。然後,我只需將條件傳遞給HABTM關係即可獲得該特定型號的媒體。例如:ObjectMedium.model => 'Template'將返回連接到模板的所有媒體。

簡而言之:我想要1個表格將任何模型鏈接到任何媒介。

的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' 
     ) 
    ); 
} 

然而,餵養它下面的數據甚至不會保存介質:

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 
      ) 

    ) 

這給了我以下查詢:

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') 

任何發生什麼問題的想法?以及如何在連接表中添加模型名稱?

+0

可能重複問題/ 6677602/CakePHP的更新 - 超現場上的habtm聯接表 – mark

回答