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

Telefone não está persistindo com o CASCADE= "persist"

Se for executado o arquivo criar-aluno.php com a linha de persistência do $telefone comentada:

//$entityManager->persist($telefone);

O doctrine cria o aluno na tabela de alunos, mas não cria os telefones correspondentes na tabela de telefones.

Descomentando e executando de novo funciona normalmente. O Doctrine está ignorando a propriedade "cascade" na classe Aluno ao que parece... mas somente na hora de persistir, pois funciona perfeitamente na hora de remover um aluno, removendo também os telefones deste. Sendo assim, solicito apoio. Desde já agradeço! Segue o código utilizado:

criar-aluno.php

<?php

use Alura\Doctrine\Entity\Aluno;
use Alura\Doctrine\Entity\Telefone;
use Alura\Doctrine\Helper\EntityManagerFactory;

require_once __DIR__ . '/../vendor/autoload.php';

$entityManagerFactory = new EntityManagerFactory();
$entityManager = $entityManagerFactory->getEntityManager();

$aluno = new Aluno();
$aluno->setNome($argv[1]);

for ($i=2; $i < $argc; $i++){
    $telefone = new Telefone();
    $telefone->setNumero($argv[$i]);
    //$entityManager->persist($telefone);
    $telefone->setAluno($aluno);
}

$entityManager->persist($aluno);
$entityManager->flush();

Classe Telefone.php

<?php

namespace Alura\Doctrine\Entity;

/**
 * @Entity
 */
class Telefone
{
    /**
     * @Id
     * @GeneratedValue
     * @Column (type="integer")
     */
    private int $id;
    /**
     * @Column (type="string")
     */
    private string $numero;

    /**
     * @ManyToOne(targetEntity="Aluno")
     */
    private Aluno $aluno;

    public function getId(): int
    {
        return $this->id;
    }

    public function setId(int $id): self
    {
        $this->id = $id;
        return $this;
    }

    public function getNumero(): string
    {
        return $this->numero;
    }

    public function setNumero(string $numero): self
    {
        $this->numero = $numero;
        return $this;
    }

    public function getAluno(): Aluno
    {
        return $this->aluno;
    }

    public function setAluno(Aluno $aluno): self
    {
        $this->aluno = $aluno;
        return $this;
    }
}

Classe Aluno.php

<?php

namespace Alura\Doctrine\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * @Entity
 */
class Aluno
{
    /**
     * @Id
     * @GeneratedValue
     * @Column(type="integer")
     */
    private int $id;
    /**
     * @Column(type="string")
     */
    private string $nome;
    /**
     * @OneToMany(targetEntity="Telefone", mappedBy="aluno", cascade={"remove","persist"})
     */
    private $telefones;

    public function __construct()
    {
        $this->telefones = new ArrayCollection();
    }

    public function getTelefones(): Collection
    {
        return $this->telefones;
    }

    public function addTelefone(Telefone $telefone): self
    {
        $this->telefones->add($telefone);
        $telefone->setAluno($this);
        return $this;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function getNome(): string
    {
        return $this->nome;
    }

    public function setNome(string $nome): self
    {
        $this->nome = $nome;
        return $this;
    }
}
2 respostas
solução!

Da uma olhada no seu for no arquivo criar-aluno.php. Ele parece estar diferente do que foi feito em aula.

O seu for está assim:

for ($i=2; $i < $argc; $i++){
    $telefone = new Telefone();
    $telefone->setNumero($argv[$i]);
    //$entityManager->persist($telefone);
    $telefone->setAluno($aluno);
}

O feito em aula está assim:

for($i = 2; $i < $argc; $i++) {
    $numeroTelefone = $argv[$i];
    $telefone = new Telefone();
    $telefone->setNumero($numeroTelefone);

    $aluno->addTelefone($telefone);
}

Altere o for e veja se isso resolve.

Erro bobo. Tinha faltado o código para adicionar o telefone no $aluno->addTelefone($telefone). Obrigado, kayke.matheus!

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