gpt4 book ai didi

php - 如何在cakephp 3中保存多条记录

转载 作者:可可西里 更新时间:2023-11-01 00:05:09 26 4
gpt4 key购买 nike

我是 cakephp 3 的新手。我想用多个复选框保存多条记录。我在事件表中有一些事件,在密码表中有一些密码。我想在每个事件下设置不同的密码。例如-对于事件 1,我想设置一些密码,这些密码将存储在 event_password_all 表中。

(id, event1, password1), (id, event1, password2), (id, event1, password3), … … (id, event1, passwordN)

我该怎么做。

这是我的 Controller 代码-

    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']);
}

&这里是 View -

<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() ?>

最佳答案

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 );
}

我没有测试过,但你明白了

>= 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);

关于php - 如何在cakephp 3中保存多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31691451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com