我在为正在使用的某些代码保存HABTM关系时遇到了一些问题。我有处于HABTM关系中的Podcasts
和Categories
。下方的代码和问题说明
Model/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
)
);
}
型号/类别.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
)
)
这将保存新类别"Test"one_answers"Test2",然后用它们新添加的id更新联接表。这是不可能的,还是我错过了这里的一些图片?
您确实可以做到这一点,但使用另一种数据格式,其中每条记录都包含相关数据,如以下代码所示,该代码允许保存2条记录:
array{
array{
'Podcast' => array {
'id' => 25
},
'Category' => array {
'name' => 'Test'
}
}
array{
'Podcast' => array {
'id' => 25
},
'Category' => array {
'name' => 'Test2'
}
}
}
将此数组传递给某个播客/类别模型上的saveAll方法。
$this->Podcast->saveAll($myData);
但请注意,因为您没有为类别提供任何id,所以它们将被创建,即使存在同名的现有类别。
如果id为25的播客不存在,它将被创建。