我是Cake的新手,并且讨论如何在单个saveall函数中插入多行, 我拿到了这张桌子,
CREATE TABLE IF NOT EXISTS `dates` (
`date` varchar(10) COLLATE utf8_unicode_ci NOT NULL
)
我正在尝试做的是让用户使用JQuery calander选择开始日期和结束日期,一旦提交此范围之间的所有日期将保存到数据库中,我已经获得了日期数组,例如:
`array(
(int) 0 => '5/8/2013',
(int) 1 => '6/8/2013',
(int) 2 => '7/8/2013',
(int) 3 => '8/8/2013',
)
` 然后我的控制器看起来像这样:
public function index(){
if ($this->request->is('post')) {
$this->Date->create();
$data = array();
$data['dates']=array();
$startDate = $this->request->data['Date']['from'];
$endDate = $this->request->data['Date']['to'];
$datesBlocked = $this->loopDates($this->request->data['Date']['from'],$this->request->data['Date']['to']);
$data['dates'][] = $this->request->data['Blockdate']['from'];
$data['dates'][] = $this->request->data['Blockdate']['to'];
/*foreach($datesBlocked as $data) {
$data['dates'][] = $data;
}*/
if($this->Date->saveAll($data)) {
$this->Session->setFlash(__('done'));
if ($this->Session->read('UserAuth.User.user_group_id') == 1) {
// $this->redirect("/manages");
}
}
}
public function loopDates($from,$to){
$blockdates = array();
$start = strtotime($from);
$end = strtotime($to);
debug($start);
$counter = 0;
for($t=$start;$t<=$end;$t+=86400) {
$d = getdate($t);
$blockdates[$counter++] = $d['mday'].'/'.$d['mon'].'/'.$d['year'];
}
debug($blockdates);
return $blockdates;
}
问题是我无法获得foreach工作,如果我取消注释foreach,我得到错误称非法字符串偏移'日期',所以我评论说并尝试只将数据的开始日期和结束日期添加到如果这样可行,那我就得到了另一个错误。
`array(
'dates' => array(
(int) 0 => '08/05/2013',
(int) 1 => '09/05/2013'
)
) ` 注意(8):数组到字符串转换[CORE \ Cake \ Model \ Datasource \ DboSource.php,第1005行]代码
因为我试图在一个字段中插入2个值...我知道它应该像......
`array(
'dates' => array( (int) 0 => '08/05/2013',
)
'dates' => array((int) 1 => '09/05/2013'
))
`但无法弄清楚该怎么做。任何帮助都会非常感激!!!!
答案 0 :(得分:0)
您希望阵列使用saveAll()
保存多个日期的结构是:
array(
'Date' => array(
0 => array(
'date' => '08/05/2013',
),
1 => array(
'date' => '09/05/2013',
)
),
)
答案 1 :(得分:0)
我知道这有点晚了,但是要在循环中写入多行,你必须使用create()继续保存。
例如:
foreach($items as $lineItem){
$this->Invoice->create();
$this->Invoice->save(array(
'user_id'=>$property['User']['id'],
'invoice_id'=>$invId['Invoices']['id'],
'item_id'=>$lineItem['item_number'],
'quantity'=>$lineItem['quantity'],
'price'=>$lineItem['mc_gross']
);
}
只是觉得值得一提,希望它能帮助别人。