3

嗨,我有一个用 cakephp 开发的网站。我有两个表:成分属性

表之间的关系是 HasAndBelongsToMany(HABTM)。这是我的模型:

class Ingredient extends AppModel {
    public $name = 'Ingredient';
    public $useTable = 'ingredients';
    public $belongsTo = 'User';

    public $hasAndBelongsToMany = array (
        'Property' => array (
            'className'             => 'Property',
            'joinTable'             => 'ingredients_properties',
            'foreignKey'            => 'ingredient_id',
            'associationForeignKey' => 'property_id',
            'unique'                => false
        )
    );

}

class Property extends AppModel{
        public $name = 'Property'; 
        public $useTable = 'properties';

}

在我的成分控制器中,我必须添加一个我在这种模式下尝试过的新属性:

$this->Ingredient->Property->create();
                $this->Ingredient->Property->set('user_id',$this->Session->read('Auth.User.id'));
                $this->Ingredient->Property->set('ingredient_id',$ing['IngredientAlias']['ingredient_id']);
                if ($this->Ingredient->Property->save($this->request->data)){
                    $this->set('flash_element','success');
                    $this->Session->setFlash ('Ingrediente modificato con successo.');
                    $this->redirect(array('action'=>'edit',$alias));
                }
                else{
                    $this->set('flash_element','error');
                    $this->Session->setFlash('Errore di salvataggio activity');
                }

向数据库中插入一条新记录,但如果我想要在成分属性(连接表)中插入一条记录的成分之间的关​​系,我该怎么做?在这种模式下,就像 Ingredients hasMany Properties 但不正确。我该如何解决?或者我必须手动将记录创建到成分属性中?

4

2 回答 2

1

您可以查看以下链接以实现相同的目的:

http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm

于 2012-09-05T06:22:04.377 回答
1

解决方案是:

class Ingredient extends AppModel {
    public $name = 'Ingredient';
    public $useTable = 'ingredients';
    public $belongsTo = 'User';

    public $hasAndBelongsToMany = array (
        'Property' => array (
            'className'             => 'Property',
            'joinTable'             => 'ingredients_properties',
            'foreignKey'            => 'ingredient_id',
            'associationForeignKey' => 'property_id',
            'unique'                => false
        )
    );

}

class Property extends AppModel{
        public $name = 'Property'; 
        public $useTable = 'properties';
        public $hasAndBelongsToMany = array (
        'Ingredient' => array (
            'className'             => 'Ingredient',
            'joinTable'             => 'ingredients_properties',
            'foreignKey'            => 'property_id',
            'associationForeignKey' => 'ingredient_id',
            'unique'                => false
        )
    );

}
于 2013-04-21T17:48:53.950 回答