cakephp HABTM同型号 [英] cakephp HABTM same model

查看:144
本文介绍了cakephp HABTM同型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站开发在cakephp 2.0
我想使一个HABTM关系同一个模型:一个产品可以有更多的产品。

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

} 

但是我有插入到我的表产品字段product_id和ingredient_id?
如何用表单保存我的数据?我知道如何使用HABTM保存数据,但我从来没有对同一个表执行HABTM。

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.

推荐答案

您的关系很好。你写的东西将创建一个产品模型,可以有任何数量的成分,并允许成分属于任何数量的产品。

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.

保存时,你必须简单地处理成分仿佛是另一个模型。保存HABTM的CakePHP示例的工作方式与将两个不同模型相关联的模型相同: http://book.cakephp.org/2.0/en/models/saving-your-data.html

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.

因此,如果您将多个Ingredients保存到产品中,则您的数组结构将如下所示:

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


数组(

     [0] =>数组(└
      ;    Product => Array(└
             id => 1

        ),

         Ingredient = >数组(

             id => 18 \\
  ;      )<
      )     1 => Array(

          Product => Array(└
        ;      id => 1

     ) ;        Ingredient => Array(└
               id =>23Æ
     )
     // ...

    )

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.

这篇关于cakephp HABTM同型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆