完整性约束违规问题:Cakephp 3.x

时间:2015-12-07 05:32:05

标签: php mysql csv cakephp-3.0

我只想将csv文件数据导入数据库表。除了我的自定义字段(日期字段(added_date))之外,所有字段都已成功插入。

显示错误。

Error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'added_date' cannot be null  

以下是插入csv数据的代码。

while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    $rs[$cnt]['client_id'] = $emapData[0];
    $rs[$cnt]['name'] = $emapData[1];
    $rs[$cnt]['address1'] = $emapData[3];
    $rs[$cnt]['address2'] = $emapData[4];
    $rs[$cnt]['county'] = $emapData[8];
    $rs[$cnt]['city'] = $emapData[6];
    $rs[$cnt]['country'] = $emapData[8];
    $rs[$cnt]['postcode'] = $emapData[7];
    $rs[$cnt]['email_label'] = $emapData[14];
    $rs[$cnt]['time_spent_on_site'] = $emapData[20];
    $rs[$cnt]['added_date'] = date('Y-m-d H:i:s'); <== gives error that integrity constrains violation.

    $cnt++;
}

fclose($file);

if (count($rs) > 0)
{
    $customers = TableRegistry::get('Customers');
    $entities = $customers->newEntities($rs);

    $customers->connection()->transactional(function () use ($customers, $entities) {
        foreach ($entities as $entity)
        {
            $customers->save($entity);
        }
    });
}

数据库表结构如下:

enter image description here

非常感谢你。

1 个答案:

答案 0 :(得分:1)

它的概念在Cakephp 3.x中引入,我们需要使用

$rs[$cnt]['added_date'] = new \DateTime('now');

取代

$rs[$cnt]['added_date'] = date('Y-m-d H:i:s'); //Deprecated in Cakephp 3.x

非常感谢你的方法。