更新蛋糕中的相关表格

时间:2014-01-12 19:14:39

标签: php cakephp sql-update database-update

我有这个:

$this->request->data['Person']['person_id'] = $this->Session->read('insertedPersonID');
$savedPerson = $this->Person->saveAll($this->request->data, array('validate'=>'first'));

更新所选人员行,但其相关表(如PersonColor和PersonParts)未更新,而是插入新行。

我认为cake会自动更新相关的表,只要主表的id是其他两个表的外键,因为这样做:

$savedPerson = $this->Person->saveAll($this->request->data, array('validate'=>'first'));

插入Person表,另外两个相关的两个表很好。

如何让它更新其他两个表?

修改 对于模型关系:

人物模型:

public $hasMany = array(
  'PersonParts' => array(
    'className' => 'Part',
    'foreignKey' => 'part_person_id'
   ),
  'PersonColors' => array(
    'className' => 'Color',
    'foreignKey' => 'color_person_id'
   )
);

零件模型:

public $belongsTo = array(
  'PartPerson' => array(
    'className' => 'Person',
    'foreignKey' => 'part_person_id'
   )
);

颜色模型:

public $belongsTo = array(
 'ColorPerson' => array(
    'className' => 'Person',
    'foreignKey' => 'color_person_id',
    'conditions' => '',
    'fields' => '',
    'order' => ''
   )
);

编辑2

var_dump $ this-> request-> data

array(3){
    ["Person"]=>array(4){
        ["person_user_id"]=>string(1)"3"
        ["person_name"]=>string(9)"Britney"
        ["person_category_id"]=>string(2)"16"
        ["visibility"]=>string(1)"1"
        ["person_id"]=>string(1)"71"
    }
    ["PersonParts"]=>array(1){
        [0]=>array(3){
            ["part_name"]=>string(4)"hands"
            ["quantity"]=>string(1)"2"
            ["part_part_type_id"]=>string(1)"1"
        }
    }
    ["PersonColors"]=>array(2){
        [0]=>array(4){
            ["color_name"]=>string(3)"blue"
            ["test_field1"]=>string(1)"8"
            ["test_field2"]=>string(1)"9"
            ["position"]=>int(1)
        }
        [1]=>array(2){
            ["color_name"]=>string(5)"red"
            ["position"]=>int(2)
        }
    }
}

注意:此var_dump仅在Person数组下显示[“person_id”] =>字符串(1)“71”作为添加字段以使蛋糕进行更新,而不是插入... person_id未显示在PersonParts和PersonColors在这里,因为它没有那样工作。我应该通过什么或如何对其他2个相关表进行更新?

1 个答案:

答案 0 :(得分:0)

要让Cake对相关表进行更新,您需要传入相关记录的id,否则Cake将不知道要更新哪条记录。

你可以在表单中将其设为隐藏字段,这就是我的工作方式。

PersonParts的var转储应该如下所示(注意额外的'part_id'字段):

["PersonParts"]=>array(1){
    [0]=>array(3){
        ["part_id"]=>string(1)"7"
        ["part_name"]=>string(4)"hands"
        ["quantity"]=>string(1)"2"
        ["part_part_type_id"]=>string(1)"1"
    }
}

如果你没有传递id,那么(从内存中)Cake将删除现有的相关记录,并添加新记录。