Solucionado (ver solução)
Solucionado
(ver solução)
8
respostas

Slim PHP com PDO duplicando a Inserção

Olá. Estou desenvolvendo uma aplicação utilizando Slim PHP, Doctrine para persistir os dados e Docker para rodar tudo.

O problema é que está inserindo duas vezes, por algum motivo.

Breve explicação: arquivo: https://github.com/GustavoFSoares/hospital/blob/master/server/public/teste.php

use HospitalApi\Model\UsuarioModel;
use HospitalApi\Entity\Usuario;

$u = new Usuario();
$u->setEmail('gustavo10.fsoares@gmail.com');

$model = new UsuarioModel();    
$model->insert($u);

Um new no Usuário que cria o Objeto da Classe, a Model tem os métodos do Doctrine implementados para fazer o insert.

public function insert($user) {
            $this->_em->persist($user);
            $this->_em->flush();
        }

Este trecho é do AbstractModel: https://github.com/GustavoFSoares/hospital/blob/master/server/src/HospitalApi/Model/AbstractModel.php

Já verifiquei o objeto antes da inserção e suspeito de algum erro nas libs do framework, mas como é pouco provável estou procurando ajuda

8 respostas

Oi Gustavo, tudo bom?

Por algum acaso, suas entidades possuem relacionamento? User se relaciona com alguma outra classe como OneToMany ou ManyToOne?

Já passei por esse tipo de coisa com o doctrine e uma boa pista é procurar por relacionamentos com persistencia em cascata (cascade persist).

Tem. Tem os mapeamentos nas classe de Pedido

/**
         * @var integer @Id
         *  @Column(name="id", type="integer")
         *  @GeneratedValue(strategy="AUTO") */
        private $id;
        /**
         * @var DateTime
         *  @Column(type="datetime") */        
        private $hora;

        /**
         * @ManyToOne(targetEntity="Usuario")
         * @JoinColumn(name="usuario_id", referencedColumnName="id") */
        private $usuario;
        /**
         * @OneToMany(targetEntity="Item", mappedBy="pedido", cascade={"persist", "remove"}) */
        private $itens;

https://github.com/GustavoFSoares/hospital/blob/master/server/src/HospitalApi/Entity/Pedido.php

Isso é um bug do Doctrine? Qual solução porque a princípio tá tudo "certo"

Cara, eu apaguei os relacionamentos. Dropei a Base e Criei novamente.

mysql> truncate usuario;
Query OK, 0 rows affected (0.17 sec)

mysql> select * from usuario;
+----+--------------+-------+----------+
| id | email        | senha | endereco |
+----+--------------+-------+----------+
|  1 | jp@gmail.com |       |          |
|  2 | jp@gmail.com |       |          |
+----+--------------+-------+----------+
2 rows in set (0.00 sec)

Mas ele ainda assim inseriu duas vezes. Acho que pode não ser bem isso.

Bom dia Gustavo,

Realmente bem estranho... Tenta rodar o entity manager com:

$em->getConnection()
  ->getConfiguration()
  ->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());

Assim a gente consegue ver as queries executadas.

Caso essa abordagem não seja o suficiente, da uma olhada no logger:

https://dev.mysql.com/doc/refman/5.7/en/query-log.html

Vendo as queries exatas que o doctrine está executando talvez fique mais claro o porque a dupla inserção =)

Foi retorno que me deu

"START TRANSACTION" INSERT INTO usuario (email, senha, endereco) VALUES (?, ?, ?) array(3) { [1]=> string(12) "jp@gmail.com" [2]=> string(0) "" [3]=> string(0) "" } array(3) { [1]=> string(6) "string" [2]=> string(6) "string" [3]=> string(6) "string" } "COMMIT"

Vou tentar agora ver os logs do MySql

Olá, desculpe ter sumido. Tive alguns problemas pessoais. Não consegui ver as query's executadas, máximo que achei foi os logs de erro, mas nada significante.

342625Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
595597Z 0 [Warning] InnoDB: New log files created, LSN=45790
762328Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
821244Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: fb681f91-275b-11e8-b94f-0242ac110002.
823398Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
823888Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
403615Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
405190Z 0 [Note] mysqld (mysqld 5.7.21) starting as process 502 ...
408124Z 0 [Note] InnoDB: PUNCH HOLE support available
408140Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
408144Z 0 [Note] InnoDB: Uses event mutexes
408148Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
408151Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
408155Z 0 [Note] InnoDB: Using Linux native AIO
408365Z 0 [Note] InnoDB: Number of pools: 1
408458Z 0 [Note] InnoDB: Using CPU crc32 instructions
409917Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
416933Z 0 [Note] InnoDB: Completed initialization of buffer pool
418986Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
430761Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
441405Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
441468Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
463152Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
463846Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
463856Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
464151Z 0 [Note] InnoDB: Waiting for purge to start
514403Z 0 [Note] InnoDB: 5.7.21 started; log sequence number 2551166
514659Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
514832Z 0 [Note] Plugin 'FEDERATED' is disabled.
515993Z 0 [Note] InnoDB: Buffer pool(s) load completed at 180314  7:47:47
519281Z 0 [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key
519419Z 0 [Note] Server hostname (bind-address): '127.0.0.1'; port: 3306
519438Z 0 [Note]   - '127.0.0.1' resolves to '127.0.0.1';
519464Z 0 [Note] Server socket created on IP: '127.0.0.1'.
527957Z 0 [Note] Event Scheduler: Loaded 0 events
528083Z 0 [Note] Execution of init_file '/var/lib/mysql-files/q5hsXivU3M' started.
530931Z 0 [Note] Execution of init_file '/var/lib/mysql-files/q5hsXivU3M' ended.
531001Z 0 [Note] mysqld: ready for connections.
Version: '5.7.21'  socket: '/tmp/tmp.jjRocNdRdU/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
531237Z 0 [Note] Giving 0 client threads a chance to die gracefully
531261Z 0 [Note] Shutting down slave threads
531265Z 0 [Note] Forcefully disconnecting 0 remaining clients
531269Z 0 [Note] Event Scheduler: Purging the queue. 0 events
531311Z 0 [Note] Binlog end
531643Z 0 [Note] Shutting down plugin 'auth_socket'
531650Z 0 [Note] Shutting down plugin 'ngram'
531653Z 0 [Note] Shutting down plugin 'partition'
531655Z 0 [Note] Shutting down plugin 'BLACKHOLE'
531659Z 0 [Note] Shutting down plugin 'ARCHIVE'
531661Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'

Alguma ideia?

solução!

O que estava acontecendo que ao levantar servidor, eu criava duas instancias na mesma porta

"start": "php -S 0.0.0.0:3001 -t /var/www/public pubic/index.php",

Para Corrigir o problema simplesmente removi depois do /

"start": "php -S 0.0.0.0:3001 -t /var/www/public",

Boa Gustavo!

As vezes os detalhes fazem toda diferença não é mesmo? Fico feliz que tenha resolvido.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software