2

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?

casperOne
  • 73,706
  • 19
  • 184
  • 253
djt
  • 7,297
  • 11
  • 55
  • 102
  • You should take a look at Doctrine's [QueryBuilder](http://www.doctrine-project.org/docs/orm/2.0/en/reference/query-builder.html). – undefined Jan 24 '12 at 19:49

3 Answers3

1

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 :)

Community
  • 1
  • 1
casperOne
  • 73,706
  • 19
  • 184
  • 253
  • @dtj Technically, the `$q =` part is not even necessary. If you just do `$q->where(...)`, that will have the same effect. –  Jan 24 '12 at 23:01
0

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.

craphunter
  • 961
  • 2
  • 13
  • 34
  • well unfortunately, there's 3 parameters in my situation. So to account for all the permutations, i would need quite a few if/else statements. Seems to be more efficient to just add to the query as needed – djt Jan 21 '12 at 18:36
0

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().