CakePHP 2.0添加相关数据失败,缺少数据库表

时间:2012-02-16 17:35:56

标签: php cakephp cakephp-2.0

我正在尝试同时将数据保存到两个模型(一个模型和相关的hasMany),并且在我的应用程序的许多地方取得了一些成功,但是这种方法似乎不适用于表/模型它强调了名称,即

//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 table 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__component。

为什么蛋糕要查找带有双重下划线名称的表?

有什么想法吗?

Issem Danny的更新:

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

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用

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

试试此链接SaveAll

答案 1 :(得分:0)

一些事情:

  • 如果您有这三个模型:Product,Component,ProductComponent,在我看来,您正在尝试设置hasAndBelongsToMany关系。 Check out the cakephp docs.

  • 使用组件作为模型名称或模型名称似乎让我感到困惑..

  • 如果你有一个表product_components的模型:你的模型应该被命名为“ProductComponent”而没有下划线(cake会自动添加它)。如果你不遵循cake的约定,你可以声明“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'
     )
);

希望有所帮助,祝你好运。