Bom dia. Fiz conforme a aula e estou tendo o seguinte erro ao executar o arquivo:
Código do arquivo list-students.php:
<?php
use Alura\Doctrine\Entity\Course;
use Alura\Doctrine\Entity\Phone;
use Alura\Doctrine\Entity\Student;
use Alura\Doctrine\Helper\EntityManagerCreator;
require_once __DIR__ . '/../vendor/autoload.php';
$entityManager = EntityManagerCreator::createEntityManager();
$studentRepository = $entityManager->getRepository(Student::class);
$studentList = $studentRepository->studentsAndCourses();
foreach ($studentList as $student) {
echo "ID: $student->id\nNome: $student->name";
if ($student->phones()->count() > 0) {
echo PHP_EOL;
echo "Telefones: ";
echo implode(', ', $student->phones()
->map(fn(Phone $phone) => $phone->number)
->toArray());
}
if ($student->courses()->count() > 0) {
echo PHP_EOL;
echo "Cursos: ";
echo implode(', ', $student->courses()
->map(fn(Course $course) => $course->nome)
->toArray());
}
echo PHP_EOL . PHP_EOL;
}
$studentClass = Student::class;
$dql2 = "SELECT COUNT(student) FROM $studentClass student";
var_dump($entityManager->createQuery($dql2)->getSingleScalarResult());
echo PHP_EOL;
$dql3 = "SELECT COUNT(student) FROM $studentClass student WHERE SIZE(student.phones) > 1";
var_dump($entityManager->createQuery($dql3)->getSingleScalarResult());
echo PHP_EOL;
$dql4 = "SELECT COUNT(student) FROM $studentClass student WHERE student.phones IS EMPTY";
var_dump($entityManager->createQuery($dql4)->getSingleScalarResult());
Código da minha classe Student:
<?php
namespace Alura\Doctrine\Entity;
use Alura\Doctrine\Repository\DoctrineStudentRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\OneToMany;
#[Entity(repositoryClass: DoctrineStudentRepository::class)]
class Student
{
#[Id, GeneratedValue, Column]
public int $id;
#[OneToMany(
mappedBy: "student",
targetEntity: Phone::class,
cascade: ["persist", "remove"],
fetch: 'EAGER'
)]
private Collection $phones;
#[ManyToMany(targetEntity: Course::class, inversedBy: "students")]
private Collection $courses;
public function __construct(
#[Column]
public readonly string $name
) {
$this->phones = new ArrayCollection();
$this->courses = new ArrayCollection();
}
public function addPhone(Phone $phone)
{
$this->phones->add($phone);
$phone->setStudent($this);
}
/**
* @return Collection<Phone>
*/
public function phones(): Collection
{
return $this->phones;
}
public function courses(): Collection
{
return $this->courses;
}
public function enrollInCourse(Course $course): void
{
if ($this->courses->contains($course)) {
return;
}
$this->courses->add($course);
$course->addStudent($this);
}
}