Ocultar la Entidad de Unión
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeActualiza la página de inicio y... ¡arruinado! En la plantilla de la página de inicio, hacemos referencia a ship.droidNames. Sabemos que esto llama a$starship->getDroidNames(). Pero eso sigue intentando utilizar la propiedaddroids que acabamos de eliminar. Arreglemos eso primero.
¿No sigue siendo una relación entre Starship y Droide?
Ahora, podríamos arreglar esto haciendo un bucle sobre $ship->starshipDroidsy cogiendo el nombre de cada uno. Pero, ¡espera! Ignora este método durante un minuto. Si te alejas, esto sigue siendo una relación entre Starship y Droid. Así que, ¿no estaría bien que pudiéramos seguir llamando a $ship->getDroids() y que devolviera una colección de objetos Droid? ¿Es posible? Absolutamente, amigo mío, absolutamente.
Arreglar el método getDroids()
Utiliza $this->starshipDroids->map() para transformar cada elemento de la colección StarshipDroiden un objeto Droid:
| // ... lines 1 - 15 | |
| class Starship | |
| { | |
| // ... lines 18 - 202 | |
| public function getDroids(): Collection | |
| { | |
| return $this->starshipDroids->map(fn (StarshipDroid $starshipDroid) => $starshipDroid->getDroid()); | |
| } | |
| // ... lines 207 - 257 | |
| } |
Ahora tenemos un método getDroids() que devuelve de nuevo una colección de objetos Droid. ¡Estupendo!
Ahora que tenemos este método, aquí abajo en getDroidNames(). En lugar de utilizar la propiedad droids, cambia al método getDroids():
| // ... lines 1 - 15 | |
| class Starship | |
| { | |
| // ... lines 18 - 223 | |
| public function getDroidNames(): string | |
| { | |
| return implode(', ', $this->getDroids()->map(fn(Droid $droid) => $droid->getName())->toArray()); | |
| } | |
| // ... lines 228 - 257 | |
| } |
Vuelve a la plantilla de la página de inicio y actualízala. ¡Ya está! Obtener los droides de una nave sigue siendo fácil. Y el resto de nuestro código no ha tenido que cambiar.
Acto 5: Droides a prueba de futuro
Abre la entidad Droid y busca getStarships(). Aún no hemos utilizado este método, pero vamos a arreglarlo también. Esto debería devolver una colección de objetos Starship. Utiliza el mismo truco de map() para transformar la colección StarshipDroid en una colección de objetos Starship:
| // ... lines 1 - 10 | |
| class Droid | |
| { | |
| // ... lines 13 - 66 | |
| public function getStarships(): Collection | |
| { | |
| return $this->starshipDroids->map(fn (StarshipDroid $starshipDroid) => $starshipDroid->getStarship()); | |
| } | |
| // ... lines 71 - 119 | |
| } |
Ocultar la entidad de unión cuando creamos la relación
Hay una última cosa de la que tenemos que ocuparnos. Cuando creamos la relación, todavía tenemos que hacer un poco de trabajo pesado creando esta entidad de unión. No es tan sencillo como $ship->addDroid($droid). Lo abordaremos en el próximo capítulo.
6 Comments
Hi,
I am struggling with the custom many to many relationship. Maybe it is because of the 'friendship relation' instead of between two different entities. In my case a user can have 2 type of friendships. 1 is having a client: the user can help the client in my project. But a Client can have an Admin-like friend, the user who is helping the client.
Below first the User Entity class:
And the UserClient Entity:
After login I get the active user by:
But I never get the relations, if I use dd($activeUser), I get this:
I dont know what I am doing wrong, but trying to get the client with the getClient(), is always empty.
Hey @Bart-V
Could you double-check that your database schema is correct and the records are saved? From the dump you shared, I see a property that's not in your User class, the
AuthGroupproperty, and that one is holding the other two relationships. Do you see the same, or did the formatting confuse me?Cheers!
Yes i have a property AuthGroup. I did erase some field, otherwise the message would be giant.
And i tried the many to many, build with the makerbundle. And a custom version. Both give empty when calling the method getClients().
I cannot find alot about a many to many friendship relation, so i am strugling.
I just noticed that your relationships between User and UserClient are
OneToManyandManyToOne. You would need to change it toManyToManyor introduce an extra entity in between to link both sides (it's like handling theManyToManyby yourself)Cheers!
Hi,
I deleted everything from the user-user relationship and started from the beginning again. I used the makerbundle again and i found the next code in the documentation:
With the makerbundle the ORM jointable, joincolumn etc is not added. So i added those lines, and it works.
You can find it here: doctine many-to-many self-referencing
Nice research, I think MakerBundle does not add those lines because it doesn't know you're adding a self-referencing property.
Well done anyway, cheers!
"Houston: no signs of life"
Start the conversation!