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

Saving HABTM associated data in cakephp


I have a little problem. My Commodity model has Has and belongs to many association with User model. In the DB they are related through commodities_users table. So, I want Cakephp to create new records in commodities_users table in DB when the new Commodity was created. But it doesn't work. My $this->request->data array (when I want saving one new commodity) looks like this

array(
    'Commodity' => array(
        'commodity_type' => '0',
        'commoditygroup_id' => '',
        'name' => 'asdfad',
        'code' => '',
        'ean' => '',
        'costprice' => '',
        'saleprice' => '12512,123',
        'default_vatrate' => '',
        'saleprice_gross' => '',
        'sync_cashconnector' => '1',
        'commoditysetting_id' => '',
        'default_amount_enabled' => '0',
        'default_amount' => '',
        'stock_min' => '',
        'stock' => '',
        'comment' => ''
    ),
    'User' => array(
        (int) 0 => array(
            'id' => '23'
        ),
        (int) 1 => array(
            'id' => '24'
        ),
        (int) 2 => array(
            'id' => '30'
        ),
        (int) 3 => array(
            'id' => '31'
         )
));

And I am saving the Commodity model this way $this->Commodity->saveAll($this->request->data);

My cakePhp version is 2.4. The relationship is

var $hasAndBelongsToMany = array(
            'User' => array(
                    'className' => 'User',
                    'joinTable' => 'commodities_users',
                    'foreignKey' => 'commodity_id',
                    'associationForeignKey' => 'user_id',
            ),
    );

What am I doing wrong ?


Solution

  • Ok, I solved it by myself. I was just so dumm and wrote the HABTM association just in Commodity Model. Adding the same for User Model fixed the problem. And the $this->reuqest->data array looked so

    array(
        'Commodity' => array(
            'commodity_type' => '0',
            'commoditygroup_id' => '',
            'name' => 'asdfad',
            'code' => '',
            'ean' => '',
            'costprice' => '',
            'saleprice' => '12512,123',
            'default_vatrate' => '',
            'saleprice_gross' => '',
            'sync_cashconnector' => '1',
            'commoditysetting_id' => '',
            'default_amount_enabled' => '0',
            'default_amount' => '',
            'stock_min' => '',
            'stock' => '',
            'comment' => ''
        ),
        'User' => array(
            'id' => array(
                '0' => '23',
                '1' => '24',
                '2' => '25'
    
    ));
    

    Thanks for your time!