Question

I've been searching for all types of solutions and it's not working. I have two models, Bredbook and Genre, in bredbook.php and genre.php, associated with HABTM. No way to save the association.

Here is the code of one model:

public $hasAndBelongsToMany = array('Bredbook' => array('className' => 'Bredbook',
'joinTable' => 'bredbooks_genres',
'foreignKey' => 'genre_id',
'associationForeignKey' => 'bredbook_id'));

Here is the form:

echo $this->Form->create('Bredbook', array('action' => 'firstConnection'));
echo $this->Form->input('Genre', array('options' => $genres, 'empty' => false));
echo $this->Form->end('Validate');

And in BredbooksController.php:

if ($this->request->data)
{
    if($this->Bredbook->saveAssociated($this->request->data))
        return $this->redirect('/bredbooks/index');
}

The creation of the bredbook is ok, but no association is created in the table bredbooks_genres. I've tried everything... any help will be welcome.

Était-ce utile?

La solution 2

I finally did it: I don't know if it's a necessary thing, but I just used cake bake to generate everything: http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

Now I need some work to rearrange all the views, but my saving is working, with the exact same code I posted first, and I think I saved some time too with all that generated behaviour I needed !

Autres conseils

You need to send Bredbook.id in your data array:

<?php
echo $this->Form->create('Bredbook');
//It can be any other attribute, but need some Breedbook data
echo $this->Form->input('Bredbook.id', array('value' => $id));
echo $this->Form->input(
    'Genre', 
     array(
        'options' =>$genres, 
        'empty' => false
    )
);
echo $this->Form->end('Validate');

Or make sure your $this->request->data looks similar to this before saving:

Array
(
    [Bredbook] => Array
    (
         //It can be any other attribute, but need some Breedbook data
        [id] => 1
    )

    [Genre] => Array
    (
        [Genre] => Array
        (
             [0] => 1
        )

    )
)

This Solution will work also work when you are creating a new Bredbook as long as you send some data of that Model, it doesn't need to be the id, you can also send name or other attributes from your Bredbook Model. If you send Bredbook.id it will not create a new record and only make the associations, but if you don't send the id and send other attributes (like name for example) it will create a new record and will associate it with the Genre data your are sending.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top