2013-03-01 76 views
0

我需要将多个复选框保存到连接表的帮助。Cakephp - 将多个复选框保存到连接表

有3个表:

  • 客户(ID,姓名,地址)
  • 产品(ID,PRODUCT_NAME,DESC)所有产品都进入了。
  • Customers_Products(ID,PRODUCT_ID,CUSTOMER_ID)< - (连接表)

步骤1:
客户选择所需产物(苹果,橙子,樱桃在复选框) 和点击<Next>按钮

第2步:
˚F填写自己的表格(姓名,地址等)。 并单击<Submit>按钮

第3步:
我节省步骤2到Customers表从步骤1至Customers_Products表个人信息和选择的产品ID(或多个)。 它确实将个人信息和产品ID保存到指定的表格中,但是当客户选择多个产品时,它不会保存产品ID。 它增加了行但产品id字段为空。

这是我的观点:

  • <?php echo $this->Form->checkbox('CustomerProduct.product.', array('value' => '1', 'style' => 'float: left; display: inline')); ?>
  • <?php echo $this->Form->checkbox('CustomerProduct.product.', array('value' => '2', 'style' => 'float: left; display: inline')); ?>
  • <?php echo $this->Form->checkbox('CustomerProduct.product.', array('value' => '3', 'style' => 'float: left; display: inline')); ?>
  • <?php echo $this->Form->input('Customers.name', array('value'=>'Jon Toshmatov')); ?>

控制器:

$this->Prospect->saveAll($this->request->data); 

型号:

public $hasAndBelongsToMany = array(
    'CustomerProduct' => array(
     'className' => 'CustomerProduct', 
     'joinTable' => 'customers_products', 
     'foreignKey' => 'customer_id', 
     'associationForeignKey' => 'product_id', 
     'unique' => 'false', 
     'dependent' => false, 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'exclusive' => '', 
     'finderQuery' => '', 
     'counterQuery' => '' 
    ) 

期望的结果: 我想保存数据按以下顺序:

 
Customers table: 
id  name 
1  Jon T 

Customers_Products *(join table)* 
id product_id customer_id 
1 4   1 
2 3   1 
3 5   1 

回答

0

的问题是,每个复选框还将添加一个“隐藏”的输入如果通过CakePHP formhelper创建的话。这个隐藏的输入被添加来确保复选框总是发送一个值(0或1),即使它们没有被检查。

但是,在您的示例中,您正在创建3个具有相同“名称”的复选框,因此每个复选框将覆盖以前的值。

,最好的办法是创建CakePHP的表单助手一个“多”复选框;

echo $this->Form->input('Product', array('multiple' => 'checkbox')); 

为了这个正常工作,应该有一个$products viewVar,包含产品ID和标签;

内部控制器:

public function some_action() 
{ 
    // your code here 

    $this->set('products', $this->Customer->Product->find('list')); 
} 

更多关于这里保存HABTM数据; http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm

注意 除非你使用你的模型不规范的名称,看来你hasAndBelongsToMany是不正确;

怀疑你的关系是Customer hasAndBelongsTo Product,不CustomerProduct

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

+0

thaJeztah, 感谢您的回复,我就能够解决问题。 问题与我的形式复选框的名字,该复选框值不正确地传递。 – 2013-03-03 20:37:25

+0

问题可以再次关闭,谢谢。 – 2013-03-03 20:37:59