-1

I have a Product model and an Image model. They have an HABTM association. Some Images exist but they are not linked to the product. Now when I save a Product I would like to link it to some unlinked images using an array of images IDs (I MUST use this array).

Here's my code:

class Image extends AppModel {
  public $useTable = 'images';
  var $hasAndBelongToMany = array(
    'Product' => array(
      'className' => 'Product',
      'joinTable' => 'products_images',
      'foreignKey' => 'id_image',
      'associationForeignKey' => 'id_product'
    )
  );
}

class Product extends AppModel {
  public $useTable = 'products';
  var $hasAndBelongToMany = array(
    'Image' => array(
      'className' => 'Image',
      'joinTable' => 'products_images',
      'foreignKey' => 'id_product',
      'associationForeignKey' => 'id_image'
    )
  );
}

class productsController extends AppController {
  public $name = 'Products';
  public $uses = array('Products', 'File');

  public function add() {
    if (!empty($this->data)) {
      $this->Product->create();
      if ($this->AnnuncioImmobiliare->save($this->request->data)) {
        $idProduct = $this->Product->getLastInsertID();
        $this->request->data['imagesIds'] = array("1", "2", "3");
        if(isset($this->request->data['imagesIds'])){
          foreach($this->request->data['imagesIds'] as $imageId){
            $this->Image->id = $imageId;
            $this->Image->save(array('Product'=>array('id'=>$idProduct)));
          }
        }
      }
    }
  }
}

This doesn't work. Where am I wrong?

Thiezar
  • 1,143
  • 2
  • 10
  • 16
  • A good post i read about this here http://www.pabloleanomartinet.com/cakephp-2-x-saving-validating-habtm-relation-example/ – Govind Totla Jun 06 '15 at 05:15

2 Answers2

0

1) you didn't provide the data, so we can't verify it's in the correct format.

2) you're using "save()" not "saveAll()" or "saveMany()" or "saveAssociated()". Just using "save()" will not save any associated model data.

Dave
  • 28,833
  • 23
  • 113
  • 183
  • I edited the post providing code for models. My question is: how data should be formatted to save (i.e. update) just the HABTM association beetween models? And what kind of save function should I use for this purpose? – Thiezar Dec 13 '13 at 22:19
  • 1
    1) what have you tried so far? 2) have you read the incredibly detailed explanation in the CakePHP book here?: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm – Dave Dec 14 '13 at 01:34
  • Yes I read it. In fact I have no problems to define HABTM association. I can easily build a form to automagically submit associated data beetween models. My problem is on saving or updating just the association when data of both models exist yet. The [documentation](http://http://book.cakephp.org/2.0/en/models/saving-your-data.html) shows me an example of formatted array used to save HABTM associations but I'm not able to let it work. Are you willing to help me with this or you'll complain me again? :-) – Thiezar Dec 14 '13 at 12:47
0

I found a solution myself! I observed how CakePHP handles $this->data->response array when data is passed using an input automagically created for HABTM associations and I found the array should be formatted like this:

array(
  'Product' => array(
    'name' => 'myProduct',
    'id' => ''
  ),
  'Image' => array(
    'Image'=>array(
      0 => '1',
      1 => '2',
      2 => '3'
    )
  )
)

So the correct code for the controller is

class productsController extends AppController {
  public $name = 'Products';
  public $uses = array('Products', 'File');

  public function add() {
    if (!empty($this->data)) {
      $this->Product->create();
      if (isset($this->request->data['imagesIds'])) {
        $this->request->data['Image'] = array('Image' => $this->request->data['imagesIds']);
      }
      if ($this->AnnuncioImmobiliare->save($this->request->data)) {
        /* success */
      }
    }
  }
}

That's it! I hope you find this useful.

Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74
Thiezar
  • 1,143
  • 2
  • 10
  • 16
  • This is not correct. You're still using `save()` instead of `saveAll()`, which won't save the associated data. (per my answer below). Also as I pointed out, you didn't provide the data in your question, yet now reformatting the data is the answer?... just seems strange. – Dave Dec 15 '13 at 14:52
  • Well it came out, both from cakephp documentation and the effective working of this code, that `save()` works just fine. I really don't understand what you mean by providing data in my question. I provided my problem in detail AND a complete code. That reformatting of the data makes the `save()` function working nicely and saving all the HABTM associations. I want to warn that with every saving of HABTM associations, the existing associations will be deleted. To avoid this just set `'unique'=> false` in the `$hasAndBelongsToMany` model variable :-) – Thiezar Dec 15 '13 at 15:56