我在保存我正在使用的某些代码的HABTM关系方面遇到了一些问题。我在HABTM关系中有Podcasts
和Categories
。下面的代码和问题说明
模型/ 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
)
)
这将保存新类别“Test”和“Test2”,然后使用新添加的ID更新连接表。这不可能,或者我在这里错过了一些图片吗?
答案 0 :(得分:0)
您可以这样做,但使用另一种数据格式,其中每条记录包含相关数据,如下面的代码所示,可以保存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的Podcast,则会创建。