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


CakePHP 2.0 Adding Related Data fails with missing database table

我试图同时将数据保存到两个模型(一个模型和相关的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(数据库表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.'));
}

表单正确地处理了这个问题,因为它显示的是一个文本区域,而不是标准输入,但是当saveAssociated运行时,我得到的响应是:

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

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

有什么想法吗?

Issem Danny的更新:

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

几件事:

  • 如果你有这三个模型:产品、组件、产品组件,在我看来,你似乎在试图设置hasAndBelongToMany关系。看看结块的文件。

  • 在型号名称中使用组件似乎让我感到困惑。

  • 如果你有一个表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'
     )
);

希望有帮助,祝你好运。

你试过使用吗

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

尝试此链接SaveAll