简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM