2

I have a site develop in cakephp 2.0 I want to make a HABTM relation to the same model: A product can has more products.

I thinked to do in this mode into my model:

class Product extends AppModel {
    public $name = 'Product';
    public $useTable = 'products';
    public $belongsTo = 'User';
    public $actsAs = array('Containable');

        public $hasAndBelongsToMany = array(
        'Ingredient' => array(
            'className' => 'Product',
            'joinTable' => 'ingredients_products',
            'foreignKey' => 'product_id',
            'associationForeignKey' => 'ingredient_id', 
            'unique' => true
        )
    );

} 

Is correct my relation? But have I to insert into my table products the field product_id and ingredient_id? And how can I save my data with a form? I know how to save data with HABTM but I never done an HABTM to the same table.

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171

1 Answers1

1

Your relation is fine. What you have written will create a Product Model that can have any number of Ingredients and allows an Ingredient to belong to any number of Products.

When saving, you must simply treat the Ingredient as if it were another Model. The CakePHP example on saving HABTM works just as well as for associating the same model as with 2 different models: http://book.cakephp.org/2.0/en/models/saving-your-data.html.

So, if you're saving multiple Ingredients to a Product, your Array structure will look like this:

Array(
    [0] => Array(
        Product => Array(
            id => 1
        ),
        Ingredient => Array(
            id => 18
        )
        ),
    1 => Array(
        Product => Array(
            id => 1
        ),
        Ingredient => Array(
            id => 23
        )
    )
    // ...
    )

It is up to you how you capture this in a form, but the form example used in the link provided above should manage this properly.

Khior
  • 1,244
  • 1
  • 10
  • 20
  • Ok thanks, I wasn't sure with my model if can I insert more ingredients into my product. (in real ingredients are products same table same model but some product can have more product inside it I hope this is clear) – Alessandro Minoccheri Oct 08 '12 at 14:32
  • You can add as many Ingredients as you need to your Product using a HABTM relationship by changing the value of 'unique' to `false` or `'keepExisting'`. This will allow you to update the relationship table with further Ingredients without deleting the existing associations. For further details on the 'unique' key, see this page here: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html – Khior Oct 08 '12 at 16:06