I was refactoring a few developers code today, and one thing I see time and time again is two queries in favour of a left join, . The problem is symfony makes result set retrieval so easy (thanks to propel of course).

Example:
To see if an author has a comment

$author = AuthorPeer::retrieveByPK($id);
$authorComments = CommentPeer::getAuthorComments($author->getAuthorId());
 
//In the model
public static function getAuthorComments($id)
{
 
    $c = new Criteria();
    $c->add(self::AUTHOR_ID, $id);
 
    return self::doSelect($c);
 
}

The reason why people would want to use this is so they can see if a comment is available. Which is a fair point if your sql is rusty ;)

$author = AuthorPeer::getAuthorComments($id);
$author = array_pop($author);
 
...
...
 
//In the model
public static function getAuthorComments($id)
{
$c = new Criteria();
$c->add(self::AUTHOR_ID, $id);
 
$c->addJoin(self::AUTHOR_ID, CommentPeer::AUTHOR_ID, Criteria::LEFT_JOIN);
$c->setLimit(1);
return self::doSelect($c);
}

As you can see the latter users a left join, which means only one database query.

One Response to “Use a join”
  1. mircara says:

    thanks

Leave a Reply