2013-11-23 48 views
0

我试图从产品导入导入产品并将它们保存到我的数据库中。现在我无法用cakePHP完成这个任务。填写“产品”表格非常容易,但很难填写“条款”并加入表格“products_terms”。我正在使用事务($ dataSource = $ this-> Supplier-> Product-> getDataSource();)来导入产品,以确保没有不完整的数据将被保存到数据库中。现在导致术语表使用术语ID的AutoIncrement,我很难填充products_terms表,因为它只有在我知道该术语的id后才可能。如果该ID尚不存在,我无法知道要填写products_terms表中的内容。见我下面用蛋糕填充连接表PHP

https://www.dropbox.com/s/pfakd7xplsvr7cc/db_erd.PNG

ERD有谁知道一个解决方案?

阵列I发送到数据库

array(
    'Product' => array(
     'slug' => 'c24b626d6701d3b07e30b233b989ff8811', 
     'product_name' => 'DAHLIA 5A', 
     'price_new' => '159.00', 
     'affiliate_url' => 'http://ad.zanox.com/ppc/?utm_source=zanox&utm_medium=banner&utm_campaign=product]]', 
     'product_id_supplier' => 'c24b626d670133d3b07e30b2b989ff8811', 
     'supplier_id' => 'zizigo_tr', 
     'feedimport_id' => (int) 1 
    ), 
    'Image' => array(
     (int) 0 => array(
      'image' => 'zizigo_tr_5290e6d296084.JPG' 
     ) 
    ), 
    'Term' => array(
     'Term' => array(
      (int) 0 => array(
       'name' => 'Tommy Hilfiger' 
      ) 
     ) 
    ) 
) 

而且我的模型:

class Product extends AppModel { 
    public $name = 'Product'; 
    public $primaryKey = 'product_id'; 

    public $hasMany = array(
     'Vote', 
     'Image' 
    ); 

    public $hasAndBelongsToMany = array(
     'Term' => array(
      'className' => 'Term', 
      'joinTable' => 'products_terms', 
      'foreignKey' => 'product_id', 
      'associationForeignKey' => 'term_id', 
      'unique' => true 
     ) 
    ); 

    public $belongsTo = array(
     'Supplier' 
    ); 
} 

class Term extends AppModel { 
    public $name = 'Term'; 
    public $primaryKey = 'term_id'; 

    public $hasAndBelongsToMany = array(
     'Product' => array(
      'className' => 'Product', 
      'joinTable' => 'products_terms', 
      'foreignKey' => 'term_id', 
      'associationForeignKey' => 'product_id', 
      'unique' => true 
     ) 
    ); 
} 
+1

显示您迄今为止尝试的某些代码可能有助于找出问题。你的模型如何关联?你目前的控制器逻辑是什么样的? – Oldskool

+0

刚刚编辑我的答案:) –

+0

导入数据的代码在哪里? –

回答

0

问题解决了。似乎需要填写Terms表格,否则cakePHP不知道要连接哪个术语。

因此,正确的解决方案是首先检查或Term是否存在,或者在Term表中插入Term,然后使用HABTM插入产品(使用插入数组中的Term的ID),这样products_terms表也将填补。