开发者

How can I save additional information to a CakePHP HABTM Join Table?

Currently, I'm unable to save a record to a HABTM join table manually. I have a table, users_products and would like to save all additional information about the order (size, quantity, color, etc...) to this join table, instead of creating a separate one.

User $hasAndBelongsTo Product

My users controller code to do so:

Configure::write('debug', 0);
        //adds product to cart
        $this->layout = ""; //async
        $user = $this->User->find('first',array('conditions'=>array('User.id'=>$this->Auth->user("id"))));
        $data['User'] = $user['User'];
        $addition =开发者_运维知识库 array('user_id' => $this->Auth->user("id"),
                            'product_id' => $id,
                            'size' => $size,
                            'quantity' => $quantity);
        $data['Product'][] = $addition;
        $this->User->create();
        if ($this->User->saveAll($data)) {
            echo $data['User']['amount_in_cart'];

        } else {
            echo $curr_cart_amt['User']['amount_in_cart'];
        }

Unfortunately, this adds a new record to the database and clears out the entire join table while doing so. Any ideas?


You need a hasMany through association. This works just like HABTM, but instead of defining the HABTM on User and on Product, you define a hasMany to your join-model and in your model-file (which you did not need before) you define a belongsTo associtions to User and to Product

Have a look in the CookBook, it es explainend very well in there: http://book.cakephp.org/view/1650/hasMany-through-The-Join-Model

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜