Search code examples
phpcakephphas-and-belongs-to-many

CakePHP and HABTM insert/save doesn't work


I'm stuck in Cakephp insert, here is what I have

-Order HABTM Address

-Address model

Here is my association in Address model :

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

I want to save/insert a new customer with one new address So, I thought the array below would work :

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' => ''
    )
)
)

The only thing that is working is when I save the Customer first and then use the array below :

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' => ''
    )
)
)

But, I still don't have the association table filled ! It only adds an entry in the Address table.


Solution

  • Yes you should specify it in both:

    Address model:

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

    Customer Model:

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