0

我是一个 cakephp 新手,我被命令使用 1.3 版本。我不明白(指南和 api 文档都没有告诉它)我如何在 POST 请求中创建 HABTM 关联。

我正在尝试酿造一种可以由许多藤蔓制成的葡萄酒。例如,我正在创建一个由“garganega”和“chardonnay”藤蔓制成的“soave”呜呜声。

POST 参数应该如何?

鉴于这些模型

class Wine extends AppModel{
    var $hasAndBelongsToMany = array(
        'Vine' => array(
            'className' => 'Vine',
            'joinTable' => 'wine_vines',
            'foreignKey' => 'wine_id',
            'associationForeignKey' => 'vine_id',
            'with' => 'WineVine',
        ),
    );
}

class Vine extends AppModel{
    var $hasAndBelongsToMany = array(
        'Wine' => array(
            'className' => 'Wine',
            'joinTable' => 'wine_vines',
            'foreignKey' => 'vine_id',
            'associationForeignKey' => 'wine_id',
            'with' => 'WineVine',
        ),
    );        
}

class WineVine extends AppModel{
    var $name = "WineVine";

    public $belongsTo = array("Wine", "Vine");
}

我尝试了这样的 POST:

Array
(
    [Wine] => Array
        (
            [denomination] => Soave DOP
            [fantasy_name] => 
            [kind] => White
        )

    [Vine] => Array
        (
            [0] => Array
                (
                    [name] => garganega
                )
            [2] => Array
                (
                    [name] => chardonnay
                )

        )

)

但它不会在 vine table 中执行任何插入,仅在 wine 中执行。这是日志:

2   INSERT INTO `wines` (`denomination`, `fantasy_name`, `kind`, `modified`, `created`) VALUES ('', '', '', '2013-10-25 17:27:14', '2013-10-25 17:27:14')       1       55
3   SELECT LAST_INSERT_ID() AS insertID     1   1   1
4   SELECT `WineVine`.`vine_id` FROM `wine_vines` AS `WineVine` WHERE `WineVine`.`wine_id` = 2      0   0   1
5   SELECT `Vine`.`id`, `Vine`.`name`, `Vine`.`created`, `Vine`.`modified` FROM `vines` AS `Vine` WHERE 1 = 1       5   5   0
6   SELECT `Wine`.`id`, `Wine`.`denomination`, `Wine`.`fantasy_name`, `Wine`.`kind`, `Wine`.`created`, `Wine`.`modified`, `Wine`.`producer_id`, `WineVine`.`id`, `WineVine`.`wine_id`, `WineVine`.`vine_id`, `WineVine`.`created`, `WineVine`.`modified` FROM `wines` AS `Wine` JOIN `wine_vines` AS `WineVine` ON (`WineVine`.`vine_id` IN (1, 2, 3, 4, 5) AND `WineVine`.`wine_id` = `Wine`.`id`)
4

1 回答 1

0

保存wine后,尝试将其 id 注入数据数组

$this->data['Wine']['id'] = $this->Wine->id;

然后调用一个重载Model::saveAssociated(),它将保存所有藤蔓并自行更新连接表。
此重载方法在以下位置进行了描述: http ://bakery.cakephp.org/articles/ccadere/2013/04/19/save_habtm_data_in_a_single_simple_format

编辑:对不起,那是蛋糕 2.x
我刚刚意识到 1.3 没有 saveAssociated 方法

编辑 2:但如果将 saveAssociated 方法的最后一行更改为,它在 cake 1.3 中确实有效

return parent::saveAll($data, $options);
于 2013-10-26T19:16:10.837 回答