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

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');
?>

最佳答案

问题是视图。从每个表单输入的开头删除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');
?>

10-08 20:12