无法保存Model CakePHP BelongsTo

时间:2014-04-27 23:50:59

标签: php cakephp cakephp-2.1 cakephp-model

我正在尝试在products表(产品)和名为brick_types的BrickTypes表之间创建belongsTo关系。我的模型如下:

class Product extends AppModel {
   public $belongsTo = array( 'BrickType' );

    public $hasAndBelongsToMany = array(
    'colour_categories' =>
        array(
            'joinTable' => 'colours_products',
            'foreignKey' => 'product_id',
            'associationForeignKey' => 'category_id',
            'with' => 'colours_products'
        )
     );
  }

我的BrickType模型如下:

class BrickType extends AppModel {
public $name = 'BrickType';
    public $useTable = 'brick_types';
    public $displayField = 'type';
    public $hasMany = array(
    'Product' =>
        array(
            'className' => 'Product',
            'foreignKey' => 'brick_type_id'
        )
     );
 }

我的brick_types表格如下:

enter image description here

我的Products表格如下:

enter image description here

有没有人知道我该怎么解决这个问题?我的模型不会保存。我尝试过saveAssociated并保存所有但没有成功。

谢谢!

1 个答案:

答案 0 :(得分:1)

您的问题不明确,我仍然试图通过举个例子给您答案: 假设有两种模型:"产品"和" BrickType"。 你想在这两个模型之间进行连接,而代码应该是这样的:

对于Model BrickType:

class BrickType extends AppModel {

        public $name        = 'BrickType';
        public $useTable    = 'brick_types';
        public $primaryKey  = 'id';
         public $belongsTo = array(
            'Product' => array(
                'className' => 'Product',
                'foreignKey' => 'brick_type_id',
                'dependent' => 'true'
            )
        );
}

适用于型号产品:

class Product extends AppModel {

        public $name         = 'Product';
        public $useTable     = 'products';
        public $primaryKey   = 'id';   
        public $displayField = 'name';


}

对于产品控制器:

class ProductsController extends AppController {
   public $uses = array('Product','BrickType');
   $products = $this->Product->find('all');
   echo "<pre>";print_r($products);exit;
}