我在cakephp 3中非常新。我想用多个复选框保存多个记录。 我在活动表&中发现了一些事件。密码表中的一些密码。 我想在每个事件下设置不同的密码。 例如 - 对于事件1,我想设置一些密码,这些密码将存储在event_password_all表中。
(id,event1,password1), (id,event1,password2), (id,event1,password3), ... ... (id,event1,passwordN)
我该怎么做。
这是我的控制器代码 -
public function add()
{
$eventPasswordAll = $this->EventPasswordAll->newEntity();
if ($this->request->is('post')) {
$eventPasswordAll = $this->EventPasswordAll->patchEntity($eventPasswordAll, $this->request->data);
if ($this->EventPasswordAll->save($eventPasswordAll)) {
$this->Flash->success(__('The event password all has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The event password all could not be saved. Please, try again.'));
}
}
$events = $this->EventPasswordAll->Events->find('list', ['limit' => 200]);
$passwords = $this->EventPasswordAll->Passwords->find('list', ['limit' => 200]);
$this->set(compact('eventPasswordAll', 'events', 'passwords'));
$this->set('_serialize', ['eventPasswordAll']);
}
&安培;这是视图 -
<div class="eventPasswordAll form large-10 medium-9 columns">
<?= $this->Form->create($eventPasswordAll) ?>
<fieldset>
<legend><?= __('Add Event Password All') ?></legend>
<?php
echo $this->Form->input('event_id', ['options' => $events]);
echo $this->Form->input('password_id', ['options' => $passwords, 'multiple' => 'checkbox']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
答案 0 :(得分:5)
3.2.8之前:
在CakePHP 3中没有像saveAll这样的事件。
你必须遍历你的选择。
示例:
$passwords = $this->request->data('password_id');
foreach ($passwords as $password) {
$data = [
'event_id' => $this->request->data('event_id'),
'password_id' => $password
];
$eventPasswordAll = $this->EventPasswordAll->newEntity();
$this->EventPasswordAll->patchEntity($eventPasswordAll, $data);
$this->EventPasswordAll->save($eventPasswordAll );
}
我没有测试它,但你明白了
&gt; = 3.2.8
使人们保持正确的轨道
从3.2.8开始,有一种方法可以提高效率。
食谱:saving-multiple-entities
$data = [
[
'title' => 'First post',
'published' => 1
],
[
'title' => 'Second post',
'published' => 1
],
];
$articles = TableRegistry::get('Articles');
$entities = $articles->newEntities($data);
$result = $articles->saveMany($entities);
答案 1 :(得分:4)
从CakePHP版本3.2.8开始,您可以一次保存多个记录。您可以使用cakephp文档中提到的以下代码。
https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-multiple-entities
$data = [
[
'title' => 'First post',
'published' => 1
],
[
'title' => 'Second post',
'published' => 1
],
];
$articles = TableRegistry::get('Articles');
$entities = $articles->newEntities($data);
$result = $articles->saveMany($entities);