简体   繁体   中英

Update Value to null on CakePhp 3.x

I have that table:

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

records:

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

How can I update the blank registry value to NULL using CakePhp 3?

I tried to use array_filter and it just keeps the value as it is in the database, I tried to put the array key 'type' => null, and the value remains blank...

Controller action:

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

Create a migration file:

php bin/cake.php bake migration fixNullValueInClientTable

Next, in your migration file put this:

<?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'=''");
    }
}

Don't forget to configure your 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

(You can add as many entries as you have server)

Execute phinx on the local env:

vendor/bin/phinx migrate -e local

And it's done.

Never fix your tables inside your app, use a migration file, this way you can mass-apply the configuration on all your DB servers on different env.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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