2013-07-07 158 views
0

对于我正在使用的某些代码,保存我的HABTM关系时遇到了一些问题。我在HABTM关系中有PodcastsCategories。代码和问题解释如下保存新关联的CakePHP HABTM关系

型号/ Podcast.php

class Podcast extends AppModel{ 
    public $hasMany = 'Episode'; 
    public $hasAndBelongsToMany = array(
     'Category' => 
      array(
       'className' => 'Category', 
       'joinTable' => 'categories_podcasts', 
       'foreignKey' => 'podcast_id', 
       'associationForeignKey' => 'category_id', 
       'unique' => false 
      ) 
     ); 
} 

型号/ Category.php

class Category extends AppModel{ 
    public $hasAndBelongsToMany = array(
     'Podcast' => 
      array(
       'className' => 'Podcast', 
       'joinTable' => 'categories_podcasts', 
       'foreignKey' => 'category_id', 
       'associationForeignKey' => 'podcast_id', 
       'unique' => false 
      ) 
     ); 
} 

这是我传递到saveAll()数组看起来像

Array 
(
    [Podcast] => Array 
     (
      [name] => Mohr Stories - FakeMustache.com 
      [description] => Join your host Jay Mohr and a rotating cast of his hilarious friends as they regale you with tales and conversation covering every topic imaginable. You haven't heard the half of it until you've heard... Mohr Stories. 
      [website] => http://www.FakeMustache.com 
     ) 

    [Category] => Array 
    (
     [0] => 1 
     [1] => 2 
    ) 

) 

工作正常 - 播客,并将连接表进行更新,但我的印象是,我Category阵列可以如下所示下:

[Category] => Array 
     (
      [0] => Array 
       (
        [name] => Test 
       ) 

      [1] => Array 
       (
        [name] => Test2 
       ) 

     ) 

这将保存新的类别“测试”和“Test2”,然后用它们新添加的ID更新连接表。这是不可能的,或者我错过了这里的一些图片?

+0

'我在印象下 - 基于什么文档? – AD7six

+0

根据[本节](http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm)的“保存您的数据”页面文档。他们的示例数组和说明_“将上面的数组传递给saveAll()将创建包含的标签,每个标签都与它们各自的配方关联。”_ – Bizarro181

回答

0

你做的是能够做到这一点,但其中每个记录包含相关的数据作为下面的代码,可以节省2个记录另一种数据格式:

array{ 
    array{ 
     'Podcast' => array { 
      'id' => 25 
     }, 
     'Category' => array { 
      'name' => 'Test' 
     } 
    } 
    array{ 
     'Podcast' => array { 
      'id' => 25 
     }, 
     'Category' => array { 
      'name' => 'Test2' 
     } 
    } 
} 

通过这个阵列到白水方法在你的一个Podcast/Category模型上。

$this->Podcast->saveAll($myData); 

,但照顾,因为你没有为类别提供任何标识,他们将创建,即使有具有相同名称的现有范畴。

而且如果与25不存在的ID的播客,它会被创建