cakephp HABTM same model

萝らか妹 提交于 2020-01-02 12:41:23

问题


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.



来源:https://stackoverflow.com/questions/12773185/cakephp-habtm-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!