CakePHP:重复输入键"PRIMARY'用于shell脚本


CakePHP: Duplicate entry for key "PRIMARY' for shell script

我正在创建一个房地产网站,列表ID附加到每个列表。我在CakePHP通过shell运行一个脚本,它正在解析一个csv文件,应该更新任何已经存在的列表或插入一个新的,如果它没有。

问题是,我一直得到一个Duplicate entry '###' for key "PRIMARY',其中###是由CSV提供的清单ID。这个脚本正在从命令行运行。

这是我的表包含的一个小版本:

CREATE TABLE `listings` (
  `ListingID` int(11) NOT NULL,
  `AccessibilityYN` varchar(50) DEFAULT NULL COMMENT 'AccessibilityYN',
  `BathsFull` int(6) DEFAULT NULL COMMENT 'BathsFull',
  `BathsPartial` int(6) DEFAULT NULL COMMENT 'BathsPartial',
  `BathsTotal` decimal(5,1) DEFAULT NULL COMMENT 'BathsTotal',
  `Beds` int(11) DEFAULT NULL COMMENT 'Beds',
  PRIMARY KEY (`ListingID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
这是我的Listing Model(注意我有public $primaryKey = 'ListingID';)
class Listing extends AppModel {
    public $name = 'Listing';
    public $primaryKey = 'ListingID'; 
    public $belongsTo = array(
        'Agent' => array(
            'className'    => 'Agent',
            'foreignKey'   => 'AgentID'
        )
    );
}
下面是我通过命令行运行的shell:
class MyShell extends AppShell {
    public $uses = array('Listing');
    public function update_imported_listings() {
       /***SOME CODE HERE TO GET THE $entry FROM THE CSV***/
        $this->Listing->ListingID = $entry['ListingID'];
        if(!$this->Listing->exists()){
            $this->Listing->create();
        }
        if($this->Listing->save($entry)){
          echo "Saved Listing";
        } else {
          echo "Listing Failed";
        }
    }
}

我知道CakePHP通常喜欢id作为数据库中使用的字段,但是我在我的模型中设置了$primaryKey = 'ListingID'。我试过在DB中将ListingID设置为Auto Increment,但那不起作用。

有人有什么想法吗?

设置ListingID没有任何作用

这一行是你的问题:

$this->Listing->ListingID = $entry['ListingID'];

无论你的主键字段在数据库中是什么,主键值总是使用Model->id属性指定。因此,将其更改为:

$this->Listing->id = $entry['ListingID'];

不需要调用exists

不需要显式检查具有特定主键值的记录是否存在。如果传递给save()的数据数组包含一个存在于db中的有效主键值,Cake将自动更新和记录,而不是创建一个新的。如果在循环中使用save(),请确保在保存之前调用create()

不要打破CakePHP的惯例,使用'id'字段作为主键。

http://book.cakephp.org/view/24/Model-and-Database-Conventions

我得到相同的错误运行cakePHP shell脚本,结果是最新记录的ID是在列的大小允许的最大值(谁使表使用一个中等int ID列),所以auto_increment不工作。更改了列,以允许修复更大的数字。可能是一些显而易见的东西,但可能会对某人有所帮助。