如何在CakePHP 2.4中保存HABTM?

时间:2014-03-01 16:35:32

标签: cakephp cakephp-2.0

cars_images

中的Car HABTM图像
Array
(
    [Car] => Array
        (
            [country_id] => 1
            [body_type_id] => 7
            [published] => 0
            [variant] => 4 cyl AWD
        )
    [Image] => Array
        (
            [image_url] => files/cars/subaru/outback/2012/Outback-3.6R3.jpg
        )
)

汽车正在救人。图像不是(没有创建记录,不在images表中,也不在cars_images表中。

由于

2 个答案:

答案 0 :(得分:0)

您需要一个如下所示的表单:

echo $this->Form->input('Image.0.image_url');
echo $this->Form->input('Image.1.image_url');
echo $this->Form->input('Image.2.image_url');

所以,产生这个:

Array
(
    [Car] => Array
        (
            [country_id] => 1
            [body_type_id] => 7
            [published] => 0
            [variant] => 4 cyl AWD
        )
    [Image] => Array
        (
           [0] => Array
                (
                    [image_url] => files/cars/subaru/outback/2012/Outback-3.6R3.jpg
                )
           [1] => Array
                (
                    [image_url] => files/cars/subaru/outback/2012/Outback-3.6R3.jpg
                )
           [2] => Array
                (
                    [image_url] => files/cars/subaru/outback/2012/Outback-3.6R3.jpg
                )
        )
)

并使用saveAll

$this->Car->saveAll($this->request->data);

您可以找到更多信息 here

答案 1 :(得分:0)

对于HABTM,数组结构必须(在您的情况下)

(
    [Car] => Array
        (
            [country_id] => 1
            [body_type_id] => 7
            [published] => 0
            [variant] => 4 cyl AWD
        )

    [Image] => Array
        (
            [Image] => Array
                  (
                    [0] => Array
                      (
                         [image_url] => files/cars/subaru/outback/2012/Outback-3.6R3.jpg
                      )
                  )
        )
)

要“保存数据”需要使用

$this->Car->saveAll($data);