CakePHP - saveAssociated / saveAll的行为类似于saveMany

时间:2015-11-25 14:45:02

标签: php cakephp

我有两个模型,即Product和ProductSpecification,它们具有以下关系:

folder2

(Product Model)
public $hasMany = array(
    'ProductSpecification' => array(
        'className' => 'ProductSpecification',
        'foreignKey' => 'product_id',
        'dependent' => true
    )
);

使用CakePHP表单助手我发布了ProductSpecification数据,然后我使用(ProductSpecification Model) public $belongsTo = array( 'Product' => array( 'className' => 'Product', 'foreignKey' => 'product_id' ) ); 方法(或saveAll,我已尝试过两者)来保存数据。 POST后,saveAssociated给出了以下输出:

debug($this->request->data)

这很好,对..?现在,调试后的行我使用以下代码保存(我也尝试过saveAssociated):

array(
    'Product' => array(
        'id' => '2'
    ),
    'ProductSpecification' => array(
        'title' => 'test',
        'step' => '1',
        'position' => '1'
    )
)

由于某些奇怪的原因,这会在我的ProductSpecification表中保存三(!)个空行,只设置if($this->Product->saveAll($this->request->data)) 字段(和product_id);字段idtitlestep为空。当我运行position时,会发生完全相同的行为。我做错了什么?

我正在运行CakePHP 2.x。

1 个答案:

答案 0 :(得分:2)

您的保存数据应该更像这样: -

array(
    'Product' => array(
        'id' => '2'
    ),
    'ProductSpecification' => array(
        array(
            'title' => 'test',
            'step' => '1',
            'position' => '1'
        )
    )
);

ProductSpecification的值需要作为hasMany关系的数字索引数组传递。

此外,请确保在传递关联数据时使用saveAssociated()而不是saveAll(),因此无需使用包装器方法(应尽可能避免使用)。

相关问题