Cakephp产品和订单之间有很多很多关系

时间:2013-12-04 02:55:57

标签: cakephp relationship

所以目前我有两个表产品和订单。他们之间的关系很多很多。我在Model Product.php中使用的代码是

        public $hasAndBelongsToMany = array
( 
    'Order'=>array
    ( 
        'joinTable' => 'ordersproducts', 
        'unique' => true, 
        'foreignKey' => 'productID',
        'associationForeignKey'  => 'orderID', 
        'order'=>'productID ASC'
    )
);

我在Model Order.php中使用的代码是

        public $hasAndBelongsToMany = array
( 
    'Product'=>array
    ( 
        'joinTable' => 'ordersproducts', 
        'unique' => true, 
        'foreignKey' => 'orderID',
        'associationForeignKey'  => 'productID', 
        'order'=>'productID ASC'
    )
);

当前功能是add(),管理员可以为客户添加订单。订单控制器中的功能代码是

public function add() {
    if ($this->request->is('post')) 
    {
        if ($this->request->is('post') || $this->request->is('put')) 
        {               
                $this->request->data['Product']['Product'] = array(); 
                foreach($this->data['Product']['checkbox'] as $k=>$v) 
                { 
                    if ($v) $this->request->data['Product']['Product'][] = $k; 

                }   

                //$this->Order->create();
                if ($this->Order->saveAll($this->request->data)) {
                    $this->Session->setFlash(__('The order has been saved'),'default',array('class' => 'good'));
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The order could not be saved. Please, try again.'),'default',array('class' => 'error'));
                }

        }
    }
    $products = $this->Order->Product->find('list',array('fields'=>array('id','name'))); 
    $this->set(compact('products'));

    $customers= $this->Order->Customer->find('list',array('order'=>'cutomer_name ASC','fields'=>array('id','cutomer_name')));
    $this->set(compact('customers')); 


}

添加订单的视图是:

    foreach ($products as $id=>$label) 
        { 
            echo "<tr>"; 
            echo "<td class='heading'>".$label."</td>"; 
            echo "<td class='data'>"; 
            echo $this->Form->input("Product.checkbox.$id", array('label'=>'','legend'=>false,'type'=>'checkbox',)); 
            echo "</td>"; 
            echo "</tr>"; 
        } 

如您所见,我使用了产品列表的复选框。现在我想知道我应该在哪里添加数量以及我需要在模型关系中进行哪些更改。我不知道该怎么做

1 个答案:

答案 0 :(得分:2)

一种方法是对HABTM关系使用'with'参数:

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm

'with'参数应引用带有外键的'OrderItem'作为订单和产品,并附加数量,单价,项目名称以及您想要添加的任何其他参数。

请注意订单,您需要确保不要过多地规范化数据,就好像您的产品稍后更改价格一样,您不希望丢失客户为此订单项支付的金额。< / p>