CakePHP 4两次保存数据



CakePHP以某种方式两次保存相同的数据。出于某种原因,我想实现这个添加方法,以便在有人直接转到domain.com/recordings/add时立即保存$dummy

它看起来很直,我一直在挠头。我已经检查了验证错误;我尝试过禁用验证;我尝试使用patchEntity()

不过,有一件奇怪的事情是,如果你点击domain.com/recordings/index中的add recording按钮(而不是在浏览器上键入url(进入domain.com/recordings/add,数据只保存一次。

控制器:

public function add()
{
$dummy = [
"user_id" => 1,
"title" => "tgfbthgdthb",
"body" => "rgcvfghfhdxcgb",
"published" => 0,
];
$recording = $this->Recordings->newEntity($dummy);
$this->Recordings->save($recording);
}

型号/表格:

public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('recordings');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER',
]);
$this->hasMany('Words', [
'foreignKey' => 'recording_id',
]);
}

型号/实体:

protected $_accessible = [
'user_id' => true,
'title' => true,
// 'slug' => true,
'body' => true,
'published' => true,
'created' => true,
'modified' => true,
'user' => true,
'words' => true,
];

视图:

<?php
/**
* @var AppViewAppView $this
* @var AppModelEntityRecording $recording
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Recordings'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="recordings form content">
<?= $this->Form->create($recording) ?>
<fieldset>
<legend><?= __('Add Recording') ?></legend>
<?php
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('title');
echo $this->Form->control('body');
echo $this->Form->control('published');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>

不要试图适应人们的懒散,不要允许他们通过访问URL(即通过GET请求(来保存数据,这只会造成麻烦,最重要的是,这是糟糕的应用程序设计。

至少实施一种适当的保护措施,只保存POST请求的数据。

浏览器可能会在各种情况下发出多个请求,从飞行前的OPTIONS请求到奇怪的怪癖,例如Firefox如果在响应数据的前x字节中找不到任何编码信息,就会中止请求,然后发出一个新的请求,该请求假定对响应进行特定编码。

public function add()
{
if ($this->request->is('post')) {
// save data here
}
}

最新更新