CAKEPHP外键约束 - Debug显示正确的值

时间:2012-02-29 14:49:50

标签: mysql cakephp foreign-keys

我正在创建我的第一个真正的CakePHP项目。我已阅读手册并浏览了博客教程,但绝不是专家。我通过使用表单助手生成的表单向数据库添加数据时遇到问题。表单有两个文本输入和一些选择框,所有这些都正确填充。当我填写表单并点击提交时,它告诉我在第一个选择框上有一个外键约束错误。但是,当我调试$ this-> request->数据时,它具有与之关联的正确值。这是调试。

Array
(
    [car] => Array
        (
        [stock] => G123456
        [vin] => 12345678
        [make_id] => 1
        [car_model_id] => 2
        [year_id] => 20
        [location_id] => 9
        [service_status_id] => 1
        [type_id] => 6
        )

)

为了确保我的架构是正确的,我直接从mysql控制台进行插入,它运行得很好。这是我跑的命令。

INSERT INTO cars (stock, vin, make_id, car_model_id, year_id, location_id, service_status_id, type_id) VALUES ('G123456', '12345678', '1', '2', '20', '9', '1', '6');

我不确定为什么它在给我打电话时给出了外键约束错误:

$car = $this->Car->save($this->request->data);

有什么想法吗?

编辑 CakePHP中的错误下的查询是:

INSERT INTO `cars` (`modified`, `created`) VALUES ('2012-02-29 15:53:21', '2012-02-29 15:53:21')

当我从mysql控制台运行该查询时,我得到了同样的错误。外键约束失败,make_id - 引用make.id

这是我的控制器中的add()函数:

public function add()
{   
    $this->set('years', $this->Car->Year->find('list'));
    $this->set('makes', $this->Car->Make->find('list'));
    $this->set('carModels', $this->Car->CarModel->find('list'));
    $this->set('locations', $this->Car->Location->find('list'));
    $this->set('types', $this->Car->Type->find('list'));
    $this->set('serviceStatuses', $this->Car->ServiceStatus->find('list'));
    if(!empty($this->request->data))
    {
        $car = $this->Car->save($this->request->data);  
        //debug($this->request->data, true);
    }
}

这是视图文件:

<?php
echo $this->Form->create('Car', array('action' => 'add'));
echo $this->Form->input('car.stock');
echo $this->Form->input('car.vin');
echo $this->Form->input('car.make_id');
echo $this->Form->input('car.car_model_id');
echo $this->Form->input('car.year_id');
echo $this->Form->input('car.location_id');
echo $this->Form->input('car.service_status_id');
echo $this->Form->input('car.type_id');
echo $this->Form->end('Add');
?>

1 个答案:

答案 0 :(得分:1)

问题在于观点。从每个表单输入的开头删除car.。这不是必需的。创建将使用Car模型作为前缀,它将解决问题。

<?php
echo $this->Form->create('Car', array('action' => 'add'));
echo $this->Form->input('stock');
echo $this->Form->input('vin');
echo $this->Form->input('make_id');
echo $this->Form->input('car_model_id');
echo $this->Form->input('year_id');
echo $this->Form->input('location_id');
echo $this->Form->input('service_status_id');
echo $this->Form->input('type_id');
echo $this->Form->end('Add');
?>