HABTM使用saveall()保存主模型

时间:2012-10-31 14:03:22

标签: cakephp cakephp-2.0 has-and-belongs-to-many

我遇到HABTM + cakephp的问题。

在我的应用程序中,我有这个模型(有关系定义):

Cliente:

public $hasAndBelongsToMany  = array(
    'TiposComercio' => array(
        'className'             => 'TiposComercio',
        'joinTable'             => 'tipos_comercio_cliente',
        'foreignKey'            => 'cliente',
        'associationForeignKey' => 'tipo_comercio'
    )
);

TiposComercio:

public $hasAndBelongsToMany = array(

    'Cliente' => array(
        'className' => 'Cliente',
        'joinTable' => 'tipos_comercio_cliente',
        'foreignKey' => 'tipo_comercio',
        'associationForeignKey' => 'cliente'
    )
);

发布表单时,我有数组$this->request->data

array(

    'Cliente' => array(
        'password' => '*****',
        'razao_social' => 'Teste',
        'responsavel' => 'responsavel',
        'cidade' => '1',
        'cep' => '13560201',
        'logradouro' => 'Log test',
        'numero' => '',
        'bairro' => '',
        'complemento' => '',
        'atividades' => '',
        'username' => 'username11',
        'TiposComercio' => array(
            (int) 0 => '1',
            (int) 1 => '4'
        )
    )

)

当我执行$ this-> Cliente-> saveAll($ this-> request-> data);在ClientesController中我有以下问题:

  • Just Cliente数据已保存。没有任何TiposComercio被保存。

怎么了?

谢谢!

1 个答案:

答案 0 :(得分:2)

您的数据阵列的结构似乎是错误的。请查看保存HABTM数据的手册:http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm

根据示例,您的数据数组应该像这样形成:

array(
    'Cliente' => array(
        'password' => '*****',
        'razao_social' => 'Teste',
        'responsavel' => 'responsavel',
        'cidade' => '1',
        'cep' => '13560201',
        'logradouro' => 'Log test',
        'numero' => '',
        'bairro' => '',
        'complemento' => '',
        'atividades' => '',
        'username' => 'username11',
    ),
    'TiposComecio' => array(
        (int) 0 => '1',
        (int) 1 => '4'
    )
)