首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CakePHP 4两次保存数据

CakePHP 4两次保存数据
EN

Stack Overflow用户
提问于 2020-08-24 04:48:23
回答 1查看 134关注 0票数 0

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

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

不过,奇怪的是,如果通过单击domain.com/recordings/add中的add recording按钮(而不是在浏览器上键入url ),数据只保存一次。

主计长:

代码语言:javascript
运行
复制
public function add()
{
    $dummy = [
        "user_id" => 1,
        "title" => "tgfbthgdthb",
        "body" => "rgcvfghfhdxcgb",
        "published" => 0,
    ];

    $recording = $this->Recordings->newEntity($dummy);

    $this->Recordings->save($recording);
}

模式/表格:

代码语言:javascript
运行
复制
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',
    ]);
}

模式/实体:

代码语言:javascript
运行
复制
protected $_accessible = [
    'user_id' => true,
    'title' => true,
    // 'slug' => true,
    'body' => true,
    'published' => true,
    'created' => true,
    'modified' => true,
    'user' => true,
    'words' => true,
];

意见:

代码语言:javascript
运行
复制
<?php
/**
 * @var \App\View\AppView $this
 * @var \App\Model\Entity\Recording $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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-24 14:24:23

不要试图适应人们的懒散,不允许他们仅仅通过访问一个GET请求来保存数据,这只会带来麻烦,而且这是糟糕的应用程序设计。

至少实现一个只为POST请求保存数据的适当的安全措施。

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

代码语言:javascript
运行
复制
public function add()
{
    if ($this->request->is('post')) {
        // save data here
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63554874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档