我正在创建一个房地产网站,每个商品均附有商品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;


这是我的列表模型(注意,我有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'。我试过在数据库中将ListingID设置为Auto Increment,但这没有用。

有人有什么想法吗?我很新鲜。

最佳答案

设置ListingID不会做任何事情

这行是你的问题:


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


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

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


您不需要呼叫存在

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

10-07 21:06