1
votes

I am trying to create a belongsTo relationship between a products table (products) and a BrickTypes table called brick_types. My models are as follows:

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'
        )
     );
  }

My BrickType model is as follows:

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'
        )
     );
 }

My brick_types table looks like:

enter image description here

And my Products table looks like:

enter image description here

Does anyone have any idea how I could troubleshoot this? My model will not save. I have tried saveAssociated and saveAll but have had no success.

Thanks!

1
"colours_products" is a table ? - s4suryapal
that table is a HABTM that links colours to products. - Camrin Parnell

1 Answers

1
votes

Your question is not clear, still i am trying to give you answer by taking one example : Let say there are two models namely : "Product" and "BrickType". You want to do joins between these two models, than code should be like this :

For 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'
            )
        );
}

For Model Product :

class Product extends AppModel {

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


}

For Products Controller :

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