views:

408

answers:

2

The following query returns one row as expected when run from phpmyadmin.

SELECT units .  * , locations .  *
FROM units, locations
WHERE units.id = '1'
AND units.location_id = locations.id
LIMIT 0 , 30 

But when I try to do it in Kohana 3:

$unit = DB::select('units.*', 'locations.*')
->from('units', 'locations')
->where('units.id', '=', $id)->and_where('units.location_id', '=', 'locations.id')
->execute()->as_array();
var_dump($unit);

It prints

array(0) { }

What am I doing wrong?

+2  A: 

I can't immediately tell what is wrong with that query builder, however, checkout this for debugging purposes.

After calling execute() on your db chain, try this.

echo Database::instance()->last_query;

This will show in plain SQL the last query performed. It will be worth looking at what the query builder generated, and how it differs to your SQL you used in phpmyadmin.

If all else fails, just use the plain query methods.

$query = "SELECT units .  * , locations .  *
FROM units, locations
WHERE units.id = :id
AND units.location_id = locations.id
LIMIT 0 , 30 ";

$unit = Db::query(Database::SELECT, $query)
          ->bind(':id', (int) $id)
          ->execute()
          ->as_array();
alex
echo Database::instance()->last_query; gives me:SELECT `locations`.*, `units`.* FROM `units`, `locations` WHERE `units`.`location_id` = 'locations.id' AND `units`.`id` = '1' It looks like bug it should be `locations`.`id` and not 'locations.id'???Using the plain query method you suggested gave me the following error:ErrorException [ Fatal Error ]: Cannot pass parameter 2 by referenceon line " ->bind(':id', (int) $id)"
pigfox
@OK, umm try removing the cast to integer, or make sure that $id is setup somewhere (can be after as it is pass by reference)
alex
A: 

You'll notice that your call to last_query returned (in the where portion):

WHERE units.location_id = 'locations.id' the value being passed for comparison is being quoted as a string, hence an empty result set. This may help you: http://kohanaframework.org/guide/api/DB#expr

As for your fatal error, double check to be sure you are passing $id explicitly (and not a referenced copy of another variable), that's all I could think of considering you aren't providing any source.

Ixmatus