Appending a WHERE clause to a Doctrine_Query

953 Views Asked by At

I have a situation where I want to assemble a Doctrine select query based on weather certain params are empty or not For example, if there was a $slug variable that was optional, i'd want something like this:

function get_bio($slug = '')
{
     $q = Doctrine_Query::create()
        ->from('Bio b');

     if (!empty($slug))
     {
          $q .= $q->where('b.slug = ?', $slug);
     }
 }

I know thats not the correct syntax, but how would I assemble something like that?

3

There are 3 best solutions below

0
On BEST ANSWER

You are treating the query object as a string rather than an object. Try this instead:

function get_bio($slug = '')
{
     $q = Doctrine_Query::create()
        ->from('Bio b');

     if (!empty($slug))
     {
          $q->where('b.slug = ?', $slug);
     }
 }

Note the call to $q->where() operates directly on the query object $q, so you do not have to assign the return value to anything (it returns a reference to the query object itself so that you can chain method calls).

Note also that if you are planning on adding multiple where clauses, you will probably want to use andWhere() instead of where().

1
On

Why don't you do just two Queries? In my opinion it doesn't make sense that you do a function for this, but only my opinion. I would do it like this way:

if ($slug != NULL) {
$q = Doctrine_Query::create()
    ->from('Bio b');
    ->where('b.slug = ?', $slug);
}
else {
$q = Doctrine_Query::create()
    ->from('Bio b');
}

This is not the correct syntax too.

1
On

Answer by dtj


Apparently, I wasn't too far off. Here's the correct syntax:

function get_bio($slug = '')
{
     $q = Doctrine_Query::create()
        ->from('Bio b');

     if (!empty($slug))
     {
          $q = $q->where('b.slug = ?', $slug);
     }
 }

As simple as removing a dot :)