Tengo una relación Muchos a Muchos definida del siguiente modo:
Las dos tablas relacionadas:
CREATE TABLE `homily` (
`homilyID` int NOT NULL AUTO_INCREMENT,
`homily` text NOT NULL,
PRIMARY KEY (`homilyID`),
) ENGINE=InnoDB
CREATE TABLE `liturgy` (
`liturgyID` int NOT NULL AUTO_INCREMENT,
`timeFK` tinyint NOT NULL,
`typeFK` tinyint NOT NULL,
`week` tinyint NOT NULL,
`day` tinyint NOT NULL,
`colorFK` tinyint NOT NULL,
`name` varchar(200) COLLATE utf8mb3_spanish_ci NOT NULL,
PRIMARY KEY (`liturgyID`),
UNIQUE KEY `timeFK` (`timeFK`,`typeFK`,`week`,`day`),
KEY `colorFK` (`colorFK`)
) ENGINE=InnoDB
Y una tabla intermedia que maneja la relación Muchos a Muchos:
CREATE TABLE `liturgy_homily_join` (
`liturgyFK` int NOT NULL,
`homilyFK` int NOT NULL,
`theme` varchar(200) COLLATE utf8mb3_spanish_ci NOT NULL DEFAULT '',
PRIMARY KEY (`liturgyFK`,`homilyFK`),
KEY `homilyFK` (`homilyFK`),
CONSTRAINT `liturgy_homily_join_ibfk_1` FOREIGN KEY (`liturgyFK`) REFERENCES `liturgy` (`liturgyID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `liturgy_homily_join_ibfk_2` FOREIGN KEY (`homilyFK`) REFERENCES `homily` (`homilyID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
Ahora yo quiero consultar a mi tabla liturgy
con un criterio y obtener todas la filas de homily
que estén relacionadas.
Para ello he intentado expresar una relación Muchos a Muchos Unidireccional en Liturgy
, tal y como explica la documentación aquí. La clase queda así:
Liturgy
namespace App\Entity;
use App\Repository\LiturgyRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: LiturgyRepository::class)]
class Liturgy
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(name:"liturgyID")]
private ?int $id = null;
#[ORM\Column(type: Types::SMALLINT, name:"timeFK")]
private ?int $timeFK = null;
#[ORM\Column(type: Types::SMALLINT)]
private ?int $week = null;
#[ORM\Column(type: Types::SMALLINT)]
private ?int $day = null;
#[ORM\Column(length: 200)]
private ?string $name = null;
#[ORM\Column(type: Types::SMALLINT, name:"typeFK")]
private ?int $typeFK = null;
#[JoinTable(name: 'liturgy_homily_join')]
#[JoinColumn(name: 'liturgyFK', referencedColumnName: 'id')]
#[InverseJoinColumn(name: 'homilyFK', referencedColumnName: 'id')]
#[ManyToMany(targetEntity: Homily::class)]
public ?Collection $homilies=null;
public function __construct()
{
$this->$homilies = new ArrayCollection();
}
public function getHomilies(): ?Collection
{
return $this->homilies;
}
public function getId(): ?int
{
return $this->id;
}
// ...
}
También he intentado una relación Muchos a Muchos Bidireccional, tal y como explica la documentación aquí.
En este caso las clases quedan así:
Liturgy
namespace App\Entity;
use App\Repository\LiturgyRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: LiturgyRepository::class)]
class Liturgy
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(name:"liturgyID")]
private ?int $id = null;
#[ORM\Column(type: Types::SMALLINT, name:"timeFK")]
private ?int $timeFK = null;
#[ORM\Column(type: Types::SMALLINT)]
private ?int $week = null;
#[ORM\Column(type: Types::SMALLINT)]
private ?int $day = null;
#[ORM\Column(length: 200)]
private ?string $name = null;
#[ORM\Column(type: Types::SMALLINT, name:"typeFK")]
private ?int $typeFK = null;
/*
#[JoinTable(name: 'liturgy_homily_join')]
#[JoinColumn(name: 'liturgyFK', referencedColumnName: 'id')]
#[InverseJoinColumn(name: 'homilyFK', referencedColumnName: 'id')]
#[ManyToMany(targetEntity: Homily::class)]
*/
#[ManyToMany(targetEntity: Homily::class, inversedBy: 'liturgies')]
#[JoinTable(name: 'liturgy_homily_join')]
public ?Collection $homilies=null;
public function __construct()
{
$this->$homilies = new ArrayCollection();
}
public function getHomilies(): ?Collection
{
return $this->homilies;
}
public function getId(): ?int
{
return $this->id;
}
public function getLiturgyID(): ?int
{
return $this->id;
}
public function setLiturgyID(int $liturgyID): static
{
$this->id = $liturgyID;
return $this;
}
public function getTimeFK(): ?int
{
return $this->timeFK;
}
public function setTimeFK(int $timeFK): static
{
$this->timeFK = $timeFK;
return $this;
}
public function getWeek(): ?int
{
return $this->week;
}
public function setWeek(int $week): static
{
$this->week = $week;
return $this;
}
public function getDay(): ?int
{
return $this->day;
}
public function setDay(int $day): static
{
$this->day = $day;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getTypeFK(): ?int
{
return $this->typeFK;
}
public function setTypeFK(int $typeFK): static
{
$this->typeFK = $typeFK;
return $this;
}
}
Homily
namespace App\Entity;
use App\Repository\HomilyRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: HomilyRepository::class)]
class Homily
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(name:'homilyID')]
private ?int $id = null;
#[ORM\Column(type: Types::TEXT)]
private ?string $homily = null;
#[ManyToMany(targetEntity: Liturgy::class, mappedBy: 'homilies')]
private Collection $liturgies;
public function __construct() {
$this->liturgies = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getHomily(): ?string
{
return $this->homily;
}
public function setHomily(string $homily): static
{
$this->homily = $homily;
return $this;
}
}
Mi problema es que en ninguno de los dos casos el código funciona. Asumiendo este código en LiturgyRepository
:
public function findHomily(string $time,string $week,string $day,string $cycle): ?array
{
$timeFK=$this->timeAssoc[$time] ?? null;
$day=$this->dayAssoc[$day] ?? null;
$cycle=$this->cycleAssoc[$cycle] ?? null;
$qb= $this->createQueryBuilder('liturgy')
->andWhere('liturgy.id > 0')
/* quitamos criterios de parámetros por el momento*/
->setMaxResults(5)
->getQuery()
->getResult()
;
dd($qb);
return $qb;
}
Si es que no entendí mal, si la relación funciona, yo debería tener en la propiedad homilies
una lista de objetos Homily
, pero siempre obtengo null
, como se puede ver en el debug:
0 => App\Entity\Liturgy {#651 ▼
-id: 1
-timeFK: 1
-week: 1
-day: 1
-name: "Domingo I de Adviento (Año A)."
-typeFK: 1
+homilies: null
}
1 => App\Entity\Liturgy {#649 ▼
-id: 2
-timeFK: 1
-week: 2
-day: 1
-name: "Domingo II de Adviento (Año A)."
-typeFK: 1
+homilies: null
Aclaro que no es un problema con los datos, las tablas tienen registros coincidentes en esas relaciones. Por ejemplo la consulta:
select
h.homilyID
from liturgy l
inner join liturgy_homily_join j
on l.liturgyID=j.liturgyFK
inner join homily h
on j.homilyFK=h.homilyID
where
l.liturgyID=1;
Me arroja todas las filas que cumplen la relación:
+----------+
| homilyID |
+----------+
| 1987 |
| 1989 |
| 1990 |
| ... |
+----------+
¿Alguien puede decirme cuál es mi error al implementar las relaciones?
EDICIÓN
Según este post en SymfonyCasts en Symfony no es posible una relación Muchos a Muchos si la tabla asociativa posee otras columnas aparte de los IDs que relacionan las tablas. Es mi caso, dado que la tabla liturgy_homily_join
tiene una columna extra que es theme
. Para resolverlo, habría que crear en la entidad de la tabla asociativa relaciones ManyToOne
con cada una de las llaves foráneas.
Haciendo eso, las clases quedarían así, pero tampoco funciona.
Liturgy
namespace App\Entity;
use App\Repository\LiturgyRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
#[ORM\Entity(repositoryClass: LiturgyRepository::class)]
class Liturgy
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(name:"liturgyID")]
public ?int $id = null;
#[ORM\Column(type: Types::SMALLINT, name:"timeFK")]
private ?int $timeFK = null;
#[ORM\Column(type: Types::SMALLINT)]
private ?int $week = null;
#[ORM\Column(type: Types::SMALLINT)]
private ?int $day = null;
#[ORM\Column(length: 200)]
private ?string $name = null;
#[ORM\Column(type: Types::SMALLINT, name:"typeFK")]
private ?int $typeFK = null;
#[ORM\OneToMany(mappedBy: 'liturgyFK', targetEntity: LiturgyHomily::class)]
public Collection $liturgies;
public function __construct()
{
$this->liturgies = new ArrayCollection();
}
public function getLiturgies(): Collection
{
return $this->liturgies;
}
public function addLiturgies(LiturgyHomily $liturgies): self
{
if (!$this->liturgies->contains($liturgies)) {
$this->liturgies[] = $liturgies;
$liturgies->setLiturgy($this);
}
return $this;
}
public function getLiturgyFK(): Collection
{
return $this->liturgyFK;
}
public function addLiturgyFK(LiturgyHomily $liturgyFK): self
{
if (!$this->liturgyFK->contains($liturgyFK)) {
$this->liturgyFK[] = $liturgyFK;
$liturgyFK->setLiturgyFK($this);
}
return $this;
}
public function getId(): ?int
{
return $this->id;
}
// ...
}
LiturgyHomily
Esta es la entidad de la tabla asociativa:
namespace App\Entity;
use App\Repository\LiturgyHomilyRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Table(name:"liturgy_homily_join")]
#[ORM\Entity(repositoryClass: LiturgyHomilyRepository::class)]
class LiturgyHomily
{
#[ORM\Id]
#[ORM\Column(name:'liturgyFK')]
#[ORM\ManyToOne(targetEntity: Liturgy::class, inversedBy: 'liturgies')]
public ?int $liturgyFK = null;
#[ORM\Id]
#[ORM\Column(name:'homilyFK')]
#[ORM\ManyToOne(targetEntity: Homily::class)]
private ?int $homilyFK = null;
public function getLiturgyFK(): ?int
{
return $this->liturgyFK;
}
public function setLiturgyFK(int $liturgyFK): static
{
$this->liturgyFK = $liturgyFK;
return $this;
}
public function getHomilyFK(): ?int
{
return $this->homilyFK;
}
public function setHomilyFK(int $homilyFK): static
{
$this->homilyFK = $homilyFK;
return $this;
}
}
El debug de la respuesta, sigue siendo una colección vacía:
0 =>
App\Entity\Liturgy {#650 ▼
+id: 1
-timeFK: 1
-week: 1
-day: 1
-name: "Domingo I de Adviento (Año A)."
-typeFK: 1
+liturgies:
Doctrine\ORM\PersistentCollection {#711 ▼
#collection:
Doctrine\Common\Collections\ArrayCollection {#659 ▼
-elements: []
}
#initialized: false
-snapshot: []
-owner:
App\Entity\Liturgy {#650}
-association:
Doctrine\ORM\Mapping\OneToManyAssociationMapping {#745 …}
-backRefFieldName: "liturgyFK"
-isDirty: false
-em:
ContainerM8dkhgs\EntityManagerGhostEbeb667 {#329 …12}
-typeClass:
Doctrine\ORM\Mapping\ClassMetadata {#623 …}
}
}
Liturgy_Homily
(1), la cual debe tener una propiedadliturgy
con relaciónManyToOne
aLiturgy
(2) y otra propiedadhomily
con relaciónManyToOne
aHomily
(3). Después en la entityLiturgy
una propiedadhomilies
relaciónOneToMany
aLiturgy_Homily
y enHomily
una propiedadliturgies
relaciónOneToMany
aLiturgy_Homily
.users_groups
que en mi caso sería la tablaliturgy_homily_join
, pero no explican que haya que hacer nada en ese entidad. De todos modos, intento lo que comentas y te cuento.