2

我想保存记录,但是在for循环中,下一个id为null,我如何在这种情况下保存记录,当找到null并保存以前的记录时,循环将停止。

 foreach($record['ProductPlan'] as $value=>$key)

{
 $ProductsUser = array('product_plan_id'=>$key,'user_node_id'=>$userNodeId, 'is_active'=>1);
                            $this->$model->UserNode->ProductPlansUserNode->create();
                            $this->$model->UserNode->ProductPlansUserNode->save($ProductsUser);

                        }   

并且错误是违反完整性约束:1048 Column 'product_plan_id' cannot be null
and in the array

   '2'
array(
'product_plan_id' => '2',
'user_node_id' => '26',
'is_active' => (int) 1
)
'3'
array(
'product_plan_id' => '3',
'user_node_id' => '26',
'is_active' => (int) 1
)
'' // This is null how can i save previous records before null?
4

3 回答 3

3

只需使用普通 if 。这是示例代码:

 foreach ($record['ProductPlan'] as $value => $key) {
    if (isset($key) && $key) {
       $ProductsUser = array('product_plan_id' => $key, 'user_node_id' => $userNodeId, 'is_active' => 1);
       $this->$model->UserNode->ProductPlansUserNode->create();
       $this->$model->UserNode->ProductPlansUserNode->save($ProductsUser);
    }
 }    
于 2013-02-13T07:50:48.523 回答
3

正如你的错误所说,

Integrity constraint violation: 1048 Column 'product_plan_id' cannot be null

您必须更改此字段以允许null在 db 中保存空记录。如果您希望 db 自行决定该列的唯一键,请创建它AUTO_INCREMENTnull因此,如果您通过该列,它将采用下一个键。

于 2013-02-13T07:50:37.570 回答
3

我认为您对 $value 和 $key 感到困惑,反之亦然

您需要在插入表之前添加一个空数组或空数组的检查试试这个

 foreach($record['ProductPlan'] as $value=>$key){
   If($key){
   $ProductsUser = array('product_plan_id'=>$key,'user_node_id'=>$userNodeId, 'is_active'=>1);
   $this->$model->UserNode->ProductPlansUserNode->create();
   $this->$model->UserNode->ProductPlansUserNode->save($ProductsUser);  
  }

}   
于 2013-02-13T09:59:06.253 回答