2014-04-27 60 views
1

我正在嘗試在產品表(產品)和名爲brick_types的BrickTypes表之間創建belongsTo關係。我的型號如下:無法保存模型CakePHP屬於

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

我的產品表如下所示:

enter image description here

有沒有人有任何想法我可以解決這個問題?我的模型不會保存。我已經嘗試saveAssociated和saveAll但沒有成功。

謝謝!

+0

「colours_products」是一張表嗎? – s4suryapal

+0

該表是一種將顏色鏈接到產品的HABTM。 –

回答

1

您的問題尚不清楚,我仍試圖通過一個例子給出答案: 假設有兩種模型,分別是:「Product」和「BrickType」。 你想要做的這兩款車型之間的連接,比代碼應該是這樣的:

對於型號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; 
} 
+0

我的模型現在沒有在信息之前填充信息。這裏是填充磚型的控制代碼: \t'$ this-> loadModel('BrickType'); \t \t $ brick_types = $ this-> BrickType-> find('list'); \t \t \t \t // echo「

" . print_r($brick_types, true) . "
」; \t \t // $ product = $ this-> BrickType-> findById($ id); \t \t // echo「
" . print_r($this->request, true) . "
」;我不知道我有一個困難的時間格式化代碼,不完全得到stackoverflow方向。 –

+0

任何想法的人? –

+0

我已經把產品控制器的代碼,我希望它能正常工作 – s4suryapal