2014-02-19 35 views
1

我试图用HasAndBelongsToMany关系保存一些数据。 这里是我的表:CakePHP不保存正确的数据在HABTM的情况下

广告:

  • ID(INT)AI
  • 名(为varchar)

展厅:

  • ID( int)AI
  • 名(为varchar)

commercials_showrooms:

  • ID(INT)AI
  • commercial_id(INT)
  • showroom_id(INT)

和我型号:

class Showroom extends AppModel 
{ 
    public $hasAndBelongsToMany = array(
     'Commercial', 
    ); 
} 

class Commercial extends AppModel 
{ 
    public $hasAndBelongsToMany = array(
     'Showroom' 
    ); 
} 

我想保存数据(硬编码现在)这样说:

$this->loadModel('Showroom'); 
$this->Showroom->saveAll(array(
      'Showroom' => array(
       'id' => 1 
      ), 
      'Commercial' => array(
       'name' => 'test' 
      ) 
     )); 

白水()返回(布尔)真实的,但是,没有保存在数据库中。 我该如何解决这个问题?

+0

尝试保存'阵列(阵列( “陈列室'=> array( 'id'=> 1 ), 'Commercial'=> array( 'name'=>'test' ) )''。另外,你的蛋糕版是什么?并且:您是否收到验证错误(您是否在保存前尝试过验证)? – Nunser

+0

我确实尝试过,这是行不通的。 我正在使用CakePHP 2.4.1 对于我试图保存的模型没有验证。 –

+0

您正在测试的方式也不正确。 – Fury

回答

1

您是否阅读了关于"Saving Related Model Data (HABTM)" in the CakePHP book的部分?

它表明与您用于数据的格式不同。

+0

我看不出有什么区别。 –

+2

区别在于额外的周围阵列,就像我说你应该尝试的阵列。但是你说那也行不通。至少它给了你不同的错误吗? – Nunser

+0

@dynamic_cast:不要只使用你看到的第一个例子 - 阅读“你也可以使用这种格式来保存几个记录和他们与saveAll()的HABTM关联的部分...” – Dave

0

,以测试你的表,如果正在尝试这种在你的控制器:

$this->loadModel('CommercialsShowroom'); 

$CommercialsShowroom = array('CommercialsShowroom'=>array(
                  'commercial_id'=>your_value, 
                  'showroom_id'=>your_value)); 
$this->CommercialsShowroom->create(); 
if ($this->CommercialsShowroom->save($CommercialsShowroom, false)){ 
    var_dump('It is saved'); 
} 

和型号配置读取戴夫链接,了解更多信息

//CommercialsShowroom model: 

     var $belongsTo = array(
     'Commercial' => array(
      'className' => 'Commercial', 
      'foreignKey' => 'commercial_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ), 
     'Showroom' => array(
      'className' => 'Showroom', 
      'foreignKey' => 'showroom_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ) 
    ); 

//Showroom model: 

    var $hasAndBelongsToMany = array(
     'Commercial' => array(
      'className' => 'Commercial', 
      'joinTable' => 'commercials_showrooms', 
      'foreignKey' => 'commercial_id', 
      'associationForeignKey' => 'showroom_id', 
      'unique' => true, 
     ) 
    ); 

//Commercial model: 

    var $hasAndBelongsToMany = array(
     'Showroom' => array(
      'className' => 'Showroom', 
      'joinTable' => 'commercials_showrooms', 
      'foreignKey' => 'showroom_id', 
      'associationForeignKey' => 'commercial_id', 
      'unique' => true, 
     ) 
    );