Nick Price
Nick Price

Reputation: 963

Symfony2/Doctrine2 Get data from two tables

I have an Alert Class with some data in it. I then have an Availability class. In my Availability class I have

/**
 * @var \Nick\AlertBundle\Entity\Alert
 *
 * @ORM\ManyToOne(targetEntity="Nick\AlertBundle\Entity\Alert")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="availability_alert_id", referencedColumnName="id")
 * })
 */
private $availabilityAlert;

So this is a foreign key back to my Alert class, linked to my Alerts class id.

I am now doing some work on the Availability data, so I have the DQL query

public function getAlertAvailability($id)
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT a.id, a.classLetter, a.flightNumber, a.alertPseudo, a.availability, a.lastUpdated
                FROM NickAlertBundle:Availability a
                WHERE a.availabilityAlert = :id
                ORDER by a.classLetter, a.lastUpdated'
        )
        ->setParameter('id', $id)
        ->getResult();
}

The way I call that is like this

public function getAvailabilityData(){
        $alerts = $this->em->getRepository('NickAlertBundle:Alert')->getActiveAlertIds();

        if (!$alerts) {
            echo "No Availability";
        }

        foreach($alerts as $alert){
            $alertId = (int)$alert['id'];
            $allAvailability = $this->em->getRepository('NickAlertBundle:Availability')->getAlertAvailability($alertId);
        }
}

So I essentially get all my active Alerts Ids, and then pass this to get my Availability for these individual Alerts.

Now I have a couple of problems.

Firstly, in the DQL query I make, I need to also get something from my Alert table (a field called command). How would I do a join in this query to get this piece of data?

Secondly, with the data that is returned, how do I access availabilityAlert in my Twig file?

UPDATE Attempt at join

public function getAlertAvailability()
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT a.id, a.classLetter, a.flightNumber, a.alertPseudo, a.availability, a.lastUpdated, u.searchCommand
                FROM NickAlertBundle:Availability a
                JOIN a.availabilityAlert u
                ORDER BY a.classLetter, a.lastUpdated'
        )
        ->getResult();
}

Upvotes: 1

Views: 1152

Answers (1)

AlpineCoder
AlpineCoder

Reputation: 627

Doctrine will load that entity as a proxy (for lazy loading) when the Availability entity is loaded.

You can access these via a normal getter / property access, but they will typically be lazy loaded by Doctrine. You can have them joined via a DQL query and the property will be hydrated with all the linked entities already loaded, see Improving Performance with a Join.

You can then access those associated entities in Twig as any other property.

Upvotes: 2

Related Questions