Symfony / Propel: How to Left Join

Contributor Icon Contributed by David Kirk     
Tag Icon Tagged: Symfony  

A JOIN is a way to connect related database tables by the common values between them. A left join contains all of the rows from the primary table plus related members of the second database if they exist. Using joins can significantly reduce the number of database queries required to render a web page. This Tech-Recipe describes how to do a left join in Symfony using Propel.


It is common to have tables linked by foreign keys. Obtaining information from the linked table can be accomplished by a left join.

In the below example, I have a primary Patient table that is linked to a Doc table by foreign keys. Not only do I want to list the associated doctor with a patient, I also want to list the associated doctor’s pager number.

Here is an cropped example schema.yml of my database structure:
propel:
patient:
id:
name: varchar(255)
doc_id:

doc:
id:
name: varchar(255)
pager: varchar(255)

First I perform my left join in my actions class:
$c = new Criteria();
$c->addJoin(PatientPeer::DOC_ID, DocPeer::ID, Criteria::LEFT_JOIN);
$this->patients = PatientPeer::doSelect($c);

Finally, I output the data in my template:
foreach ($patients as $patient):
echo $patient->getDoc()->getPager();
endforeach;

While this template code would work without the join, this technique with the join is more efficient. Without the join, the getDoc() method of the Patient model would have to make an extra database query for each iteration of the loop. With the join, the data required to hydrate the Doc objects and the Patient data are all gathered with a single database query.

 

6 Comments -


  1. Ken Andrew said on December 3, 2008

    hi, can i join two tables from two different databases?
    from you example, what if “patient” table is in patient_db and “doc” table is in doc_db? would that be possible?

    thanks :D

  2. pawel said on March 18, 2009

    This is not working – I can’t get $patient->getDoc() to working – there’s no such method… It’s not generated with build-model :(

  3. Name said on August 21, 2009

    Anyone know the answer to this? I also need to do a join between two databases.

  4. Krzysiek said on October 27, 2009

    It could also be called getDocs if its not 1:1 relationship, or getDocRelatedByDocId().

  5. Dan said on May 27, 2010

    this is much easier to do in Doctrine since you can explicitly set the database name in the mapping. Switch!!

  6. Akhilesh Sharma said on March 8, 2011

    how we retreive values from two different tables by using this code

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -