CakePHP和HABTM插入/保存不起作用

时间:2012-12-08 13:06:02

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

我陷入了Cakephp插入,这就是我所拥有的

- 订购HABTM地址

- 地址模型

这是我在地址模型中的关联:

public $hasAndBelongsToMany = array(
    'Address' => array(
        'className' => 'Address',
        'joinTable' => 'address_customers',
        'foreignKey' => 'customer_id',
        'associationForeignKey' => 'address_id'  
    )
);

我想使用一个新地址保存/插入新客户 所以,我认为下面的数组可行:

array(
'Customer' => array(
    'nom' => 'Khiami',
    'prenom' => 'TEST',
    'tel' => '0945454545',
    'ptel' => '',
    'commentaire' => '',
    'email' => '',
    'anniversaire' => array(
        'day' => '08',
        'month' => '12',
        'year' => '2012'
    ),
    'createdFrom' => 's'
),
'Address' => array(
    (int) 0 => array(
        'adresse' => 'ADDR TEST',
        'cp_id' => '1',
        'etage' => '',
        'residence' => '',
        'batiment' => '',
        'appartement' => '',
        'type' => 'l',
        'code_sonette' => '',
        'code_portail' => '',
        'code_batiment' => '',
        'code_asc' => ''
    )
)
)

唯一有效的方法是先保存客户,然后使用下面的数组:

array(
(int) 0 => array(
    'Customer' => array(
        'customer_id' => '394'
    ),
    'Address' => array(
        'adresse' => 'ADDR TEST',
        'cp_id' => '1',
        'etage' => '',
        'residence' => '',
        'batiment' => '',
        'appartement' => '',
        'type' => 'l',
        'code_sonette' => '',
        'code_portail' => '',
        'code_batiment' => '',
        'code_asc' => ''
    )
)
)

但是,我仍然没有填充关联表!它只在地址表中添加一个条目。

2 个答案:

答案 0 :(得分:0)

由于您在HABTM关系中指定了连接表,我怀疑它是一个命名约定问题。

您是在保存地址还是客户模式?因为如果你从地址模型中调用它,我想应该已经有了一个客户,在这种情况下你只需要设置:

$this->request->data['Customer']['Customer'] = $customer_id; 

并保存地址数据,它应该在表中创建HABTM关联。

答案 1 :(得分:0)

是的,您应该在两者中指定它:

地址模型:

public $hasAndBelongsToMany = array(
   'Customer' => array(
       'className' => 'Customer',
       'joinTable' => 'address_customers',
       'foreignKey' => 'address_id',
       'associationForeignKey' => 'customer_id'  
));

客户模式:

 public $hasAndBelongsToMany = array(
   'Address' => array(
      'className' => 'Address',
      'joinTable' => 'address_customers',
      'foreignKey' => 'customer_id',
      'associationForeignKey' => 'address_id'  
));