cakephp HABTM same model

2019-05-20 14:01发布

问题:

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.

回答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.