Saving data from hasMany and belongsTo

121 views Asked by At

I am currently having some trouble with cakephp. I already try to find an answer on this forum, but nothing really usefull in my case :( Here is my problem :

I have 2 table :

Author  | Role
id      | id
role_id | name

I set my Author "belongsTo Role" and my Role "HasMany Author"

On my view, my form looks like this :

$this->Form->create('Role')
$this->Form->input('name'));
$this->Form->input('Author.id', array('type' => 'select', 'multiple' => true, 'options' => $authors));

My Role controller :

function index() {
    if (!empty($this->data)) {
        if ($this->Role->saveAll($this->data)) {
        }
    }
    $this->set('authors', $this->Role->Author->find('list'));
}

But when I try to save, my new Role in well created, but it also create a new author row instead of update the existing one. All i want, is to update the role_id from the Author table when i create a new Role. Any idea what's wrong ?

Edit: I also get the same result with $this->request->data Instead of $this->data My data looks like this when I create a new Role assigned with 2 Authors:

array(
    'Role' => array(
        'name' => 'test',
    ),
    'Author' => array(
        'id' => array(
            (int) 0 => '1',
            (int) 1 => '3'
        )
    )
)

Thanks for your help.

1

There are 1 answers

5
drmonkeyninja On

To start with your save data is not in the correct format. You can't set the Author.id to be an array, it is expecting an integer so therefore isn't updating your existing data.

Not 100% sure that this will work but try rewriting the save data like this:-

$authorIds = Hash::extract($this->request->data, 'Author.id.{n}');

foreach ($authorIds as $authorId) {
    $authors[] = [
        'id' => $authorId
    ];
}

$data = [
    'Role' => $this->request->data['Role'],
    'Author' => $authors
];

Then use $this->Role->saveAll($data). (I'm sure there's a more elegant way of writing this, just some quick example code).