quando executo o arquivo de buscar de alunos por curso, o terminal devolve esse erro:
PHP Fatal error: Uncaught TypeError: Return value of Alura\Doctrine\Entity\Student::getCursos() must implement interface Doctrine\Common\Collections\Collection, null returned in /home/oem/php/doctrine-orm/src/Entity/Student.php:85 Stack trace:
#0 /home/oem/php/doctrine-orm/commands/findStudentForClass.php(33): Alura\Doctrine\Entity\Student->getCursos()
#1 {main} thrown in /home/oem/php/doctrine-orm/src/Entity/Student.php on line 85
<?php
namespace Alura\Doctrine\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* @Entity
*/
class Student {
/**
* @ID
* @GeneratedValue
* @Column(type="integer")
*/
private $id;
/**
* @Column(type="string")
*/
private $nome;
/**
* @OneToMany(targetEntity="Phone", mappedBy="student", cascade={"remove", "persist"})
*/
private $phones;
/**
* ManyToMany(targetEntity="Curso", mappedBy="student")
*/
private $cursos;
public function __construct()
{
$this->phones = new ArrayCollection();
$this->cursos = new ArrayCollection();
}
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;
}
public function addPhone(Phone $phone): self
{
$this->phones->add($phone);
$phone->setStudent($this);//definindo q o telefone pertence ao aluno apos add o telefone.
return $this;
}
public function getPhone(): Collection
{
return $this->phones;
}
public function addCurso(Curso $curso): self
{
if ($this->cursos->contains($curso)) {
return $this;
}
$this->cursos->add($curso);
$curso->addStudent($this);
return $this;
}
/**
* @return Curso[]
*/
public function getCursos(): Collection
{
return $this->cursos;
}
}
<?php
use Alura\Doctrine\Entity\Phone;
use Alura\Doctrine\Entity\Student;
use Alura\Doctrine\Helper\EntityManagerFactory;
require_once __DIR__ . "/../vendor/autoload.php";
$entityManagerFactory = new EntityManagerFactory();
$entityManager = $entityManagerFactory->getEntityManager();
$studentsRepository = $entityManager->getRepository(Student::class);
/**
* @var Student[] $students
*/
$students = $studentsRepository->findAll();
foreach ($students as $student) {
$phones = $student
->getPhone()
->map(function(Phone $phone){
return $phone->getPhoneNumber();
})
->toArray();
echo "Id: {$student->getId()}\n";
echo "Nome: {$student->getNome()}\n";
echo "Telefone: " . implode(", ", $phones) . "\n";
$allClass = $student->getCursos();
foreach ($allClass as $class) {
echo "\tID Curso: {$class->getId()}\n";
echo "\tCurso: {$class->getName()}\n";
echo "\n";
}
echo "\n";
}