saveAll:保存相关模型的新数据或使用现有记录

时间:2013-07-10 21:04:29

标签: cakephp cakephp-2.0

我正在尝试使用一种表单更新许多货件的数据。

Shipment模型belongsTo Shippingaddress模型和Shippingaddress hasMany Shipment

在界面中,用户可以使用他之前从选择字段中保存的Shippingaddress或填写小表格并添加新表格。

目前发布到控制器的数据示例结构如下所示:

array(
        (int) 0 => array(
            'Shipment' => array(
                'id' => '223',
                'shippingaddress_id' => '8',
            )
        ),
        (int) 1 => array(
            'Shipment' => array(
                'id' => '224',
                'shippingaddress_id' => '',
            ),
            'Shippingaddress' => array(
                'recipient' => 'some name',
                'address' => 'some addres data',
                'zip' => '00-555',
                'city' => 'some city',
            )
        ),
        (int) 2 => array(
            'Shipment' => array(
                'id' => '225',
                'shippingaddress_id' => '12',
            )
        )
    )

保存Shiippingaddress数据并使用

更新一次交易中的所有货件会很不错

$this->Shipment->saveAll($data)

有可能吗?

我尝试了多种已发布的数组结构,但没有成功。

1 个答案:

答案 0 :(得分:0)

您的$data结构应如下所示:

$data = array(
    'Shippingadress' => array(
        '0' => array(
            'id' => '8',
            'Shipment' => array(
                'id' => '223'
            )
        ),
        '1' => array(
            'recipient' => 'some name',
            'address' => 'some addres data',
            'zip' => '00-555',
            'city' => 'some city'
            'Shipment' => array(
                'id' => '224'
            )
        ),
        '2' => array(
            'id' => '12',
            'Shipment' => array(
                'id' => '255'
            )
        ),
    )
);

保存使用saveMany:

$this->Shippingadress->saveMany($data, array('deep' => true) );

您不需要指定shippingadress_id来清空字符串,因为Cake已经处理它并根据模型的关系放置所有相关的外键。