繁体   English   中英

在 CakePhp 3.x 上将值更新为 null

[英]Update Value to null on CakePhp 3.x

我有那张桌子:

CREATE TABLE `clients` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `created` timestamp NULL DEFAULT NULL,
  `type` varchar(5) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

记录:

insert  into `clients`(`id`,`name`,`created`,`type`) values 
(1,'test1','2020-08-07 13:58:35',''),
(2,'test2','2020-08-07 13:58:53','1'),
(3,'test3','2020-08-07 13:58:55','1');

如何使用 CakePhp 3 将空白注册表值更新为 NULL?

我尝试使用array_filter,它只是将值保留在数据库中,我尝试将数组键'type' => null,并且值保持空白......

Controller 动作:

public function edit($id = null)
{
  if (empty($id)) {
    $this->Flash->error(__('This page can not be access'));
    return $this->redirect(['action' => 'index']);
  }
 try {
    $client = $this->Clients->get($id);
  } catch (\Throwable $th) {
    $this->Flash->error(__('Client not found'));
    return $this->redirect(['action' => 'index']);
  }
  if ($this->getRequest()->is(['patch', 'post', 'put'])) {
    $post = array_filter($this->getRequest()->getData());
    $client = $this->Clients->patchEntity($client, $post);
    if($this->Clients->save($client)){
      $this->Flash->success(__('Client data has updated.'));
    } else {
      $this->Flash->error(__('Error!'));
    }
  }
  $this->set(compact('client'));
}

创建迁移文件:

php bin/cake.php bake migration fixNullValueInClientTable

接下来,在您的迁移文件中放置以下内容:

<?php

use Migrations\AbstractMigration;

class FixNullValueInClientTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->query("UPDATE clients SET 'type' = NULL WHERE 'type'=''");
    }
}

不要忘记配置您的 phinx.yml:

paths:
  migrations:
    - "%%PHINX_CONFIG_DIR%%/config/Migrations"
  seeds:
    - "%%PHINX_CONFIG_DIR%%/config/Seeds"

environments:
  default_migration_table: phinxlog
  default_database: YOURDATABASE
  local:
    adapter: mysql
    host: YOURHOST
    name: YOURDATABASE
    user: USER
    pass: PASSWORD
    port: 3306
    charset: utf8

(您可以添加与服务器一样多的条目)

在本地环境中执行 phinx:

vendor/bin/phinx migrate -e local

它已经完成了。

永远不要在您的应用程序中修复您的表,使用迁移文件,这样您就可以在不同环境的所有数据库服务器上大规模应用配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM