-1

I'd like to use db_select in a static public function of a certain class. The query should be a base query, which may then be customized in the calling function. Returning the result sets seems to work, but I'd like to return the drupal db_select-object for further usage. Here is some example code:

class foo{ 
 public static function get_query() {
  $query = db_select('bar', 'b'); 
  return $query;
 }
} 
function test() { 
  $qobj = foo::get_query(); 
  $qobj->fields('b', array('id', 'name'));
  $result = $qobj->execute();
  ...
}

The returned object seems not to be a db_select object, which can be edited further more. Do I have to create a dummy db_select and pass the reference of this object to the static function.

Thank you.

Sven

1
  • "The returned object seems not to be a db_select object" - could you please post a result of dpr or var_dump called on a returned object? That way you (and we) would know, not only seem.
    – Mołot
    Nov 6, 2013 at 9:14

1 Answer 1

2

There's no such class as db_select, but your code will return a valid SelectQuery.

class foo{ 
 public static function get_query() {
  $query = db_select('bar', 'b'); 
  return $query;
 }
} 
function test() { 
  $qobj = foo::get_query(); 

  // Get type of object
  dpm(get_class($qobj));

  // Alter the query string and make sure it has been altered
  $qobj->fields('b');
  dpm((string) $qobj);

}
test();

The first Devel output for the above is SelectQuery, as expected. The second is the following query string:

SELECT b.*
FROM 
{bar} b

Now add another function to the mix:

function test2() { 
  $qobj = foo::get_query(); 
  $qobj->fields('b', array('x'));
  dpm((string) $qobj);
}

Run that in the same page request, and you get this query string

SELECT b.x AS x
FROM 
{bar} b

So your code works exactly as you've specified that it should do.

If you're expecting something else to happen, it would be a good idea to detail that in the question.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.