Zorpen
Zorpen

Reputation: 445

Symfony 2 + Doctrine, joining 3 tables

I have 3 entities: Game, Platform (like PC, XBOX, PS3 and so on) and Image.

Game can be released on many platforms, platform can be related to many games, and finally game can have many box covers (for example one for each platform).

I want to relate those 3 entities by join table. I did some reading and found that i should create another entity to describe relations, and I did.

Now I have 4th entity GameCovers with fields: game_id, platform_id and image_id. Everything seems to work - doctrine generated getters and setters. My question is how do I fetch data from DB?

In Game Enity now I have method:

/**
* Get game_covers
*
* @return Doctrine\Common\Collections\Collection 
*/
public function getGameCovers()
{
   return $this->game_covers;
}

But how do i fetch box cover for just one platform for example: PC?

Upvotes: 1

Views: 2983

Answers (2)

fd8s0
fd8s0

Reputation: 1927

That's easy, $em->getRepository('GameCover')->findOneBy(array('platform' => $platform, 'game' => $game)) where platform and game are the respective objects, or ids.

You can use a custom repository for GameCover to do this for you under a different method.

If you use getGameCovers you'll trigger the initialisation of the proxy holding all the game covers and doctrine will fetch all of them from the database. So if you don't want to do this, just fetch the specific one you want from the GameCover repository.

Upvotes: 0

Jovan Perovic
Jovan Perovic

Reputation: 20193

You should take a look at custom entity repositories: http://symfony.com/doc/2.0/book/doctrine.html#custom-repository-classes

Inside each of methods you would then createQuery, e.g.:

# Fetch all the games that have PC release
public function getPcGames(){
    $q = $entityManager->createQuery("SELECT gc,p,g FROM GameCover gc JOIN gc.platform p JOIN gc.game g WHERE p.name = :platformName");
    $q->setParameter('platformName', 'PC');
    return $q->getResult();
}

This is, obviously, over simplified example but the key point is not to rely on getters but rather create your own queries....

Upvotes: 1

Related Questions