Question

I can't seem to update the foreign key of a child in a hasMany relationship in a parent's edit function. I've checked the data and I'm definitely passing a different parent ID, but regardless of what I try, it sets the parent id as the ID of the parent that I'm editing.

Here is what the $_POST data is giving me:

    {
        "Parent" => {
            "id" => "4",
          "name" => "Parent"
        },
        "Child" => {
            "1" => {
                  "parent_id" => "0",
                  "id" => "1"
            }
        }
    }

When I take a look at which SQL query it is running, and I get this:

 UPDATE `cakephp`.`children` SET `parent_id` = 4, `id` = 1,
`modified` = '2014-01-31 15:37:27' WHERE `cakephp`.`children`.`id` = '1'

I'm using the saveAll() function, but I'm willing to try other methods. Is there any way to work around this? I've searched around but can't seem to find a fix for my issue.

My main goal is to remove the association from the parent but still keep the data of both. This will allow me to free up the child to be associated with other models.

Please let me know if I'm missing any important details!

Était-ce utile?

La solution

So you have to change your strategy now: use updateAll as given below:

$this->Parent->recursive = -1; // free from all association
$this->Parent->updateAll(array('name'=>$myArray['Parent']['name']),
                 array('id'=>$myArray['Parent']['id']));
$lastId = $this->Parent->getLastInsertID();

Similarly with Child model

$this->Child->recursive = -1; // free from all association        
$this->Child->updateAll(array('parent_id'=>$lastId),
                 array('id'=>$myArray['Child']['1']['id']));

if Child index has more than one array inside then

$updateCondtion = Set::classicExtract($myArray, 'Child.{n}.id');
$this->Child->updateAll(array('parent_id'=>$lastId),
                 array('id'=>$updateCondtion));

  $myArray =     {
        "Parent" => {
            "id" => "4",
          "name" => "Parent"
        },
        "Child" => {
            "1" => {
                  "parent_id" => "0",
                  "id" => "1"
            }
        }
       }

Different approach altogether!

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