2012-02-16 124 views
0

我试图同时将数据保存到两个模型(一个模型和相关的hasMany),并且在我的应用程序中的多个位置已经取得了一些成功,但是此方法不会“不像是会与已经强调名称表/模型来工作,即CakePHP 2.0添加相关数据失败并丢失数据库表

//View Code 
echo $this->Form->create('Product'); 
    echo $this->Form->input('name',array('between' => '<br />')); 
    echo $this->Form->input('Component.0.text',array('between' => '<br />')); 
echo $this->Form->end(__('Submit')); 

//Controller Code 
if ($this->Product->saveAssociated($this->request->data)) { 
    $this->Session->setFlash(__('The product has been saved')); 
    $this->redirect(array('action' => 'index')); 
} else { 
    $this->Session->setFlash(__('The product could not be saved. Please, try again.')); 
} 

上述工作正常,但是我有一个模型ProductComponent(db表product_components)

//View Code 
echo $this->Form->create('Product'); 
    echo $this->Form->input('name',array('between' => '<br />')); 
    echo $this->Form->input('ProductComponent.0.text',array('between' => '<br />')); 
echo $this->Form->end(__('Submit')); 

//Controller Code 
if ($this->Product->saveAssociated($this->request->data)) { 
    $this->Session->setFlash(__('The product has been saved')); 
    $this->redirect(array('action' => 'index')); 
} else { 
    $this->Session->setFlash(__('The product could not be saved. Please, try again.')); 
} 

的形式采摘这是正确的,因为它显示的是Textarea而不是标准输入,但是当saveAssociated运行时,我得到响应:

找不到模型ProductComponent的数据库表product__components。

为什么蛋糕要找一张带有双下划线名称的桌子?

任何想法?

为Issem丹尼更新:

public $hasMany = array(
    'ProductComponent' => array(
     'className' => 'Product_Component', 
     'foreignKey' => 'product_id', 
     'dependent' => false, 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'exclusive' => '', 
     'finderQuery' => '', 
     'counterQuery' => '' 
    ) 
     ); 
+0

您可以发布您的模型,以便我们可以看到您的关系设置?我的猜测是那里出了问题。您是否在您的ProductComponent模型中设置了$ useTable属性? – 2012-02-16 19:30:54

+0

我认为你是对的,我刚刚发现我错误地输入了hasMany产品定义中的类名,这将解释为什么它在单独使用时会起作用。如果你发布了正确的答案,我会相信你的。 – 2012-02-19 14:25:58

回答

0

有几件事情:

  • 如果你有THES e三个模型:产品,组件,产品组件,在我看来你试图设置hasAndBelongsToMany关系。 Check out the cakephp docs.

  • 使用组件作为或模型中的名字似乎困惑,我..

  • 如果你有一台product_components模型:你的模型应该被命名为“ProductComponent”无下划线(蛋糕将增加自动)。如果你不遵循蛋糕的惯例,你可以声明“useTable”属性。您的模型应该是这样的:

代码:

// model 

class ProductComponent extends AppModel { 
    public $name = "ProductComponent"; 

    // Only needed when not following cake's conventions 
    public $useTable = "product_components"; 

    // rest of model code ... 
} 

// And the hasmany relation 

public $hasMany = array(
    'ProductComponent' => array(
     'className' => 'ProductComponent', 
     'foreignKey' => 'product_id' 
    ) 
); 

希望帮助,祝你好运。

+0

非常感谢Danny ...第一个例子中的组件只是一个例子来保存复制编码出另一个控制器,所以不需要HABTM。与hasMany问题虽然点,但谢谢 – 2012-02-19 23:13:36

0

您是否尝试过使用

$this->Product->saveAll($this->data)) 

尝试此链接SaveAll

+0

嗨亚历克斯,是的,我用saveAll和saveAssociated,这个问题似乎是在关系某处作为访问ProductComponent直接罚款 – 2012-02-19 14:23:07