views:

179

answers:

3

I'm using Postgres with Kohana 3's ORM module and would like to run a SELECT using a postgres function to convert values already in the database to lower case before doing the comparison.

In SQL I would write:

select * from accounts where lower(email) = '[email protected]';

In Kohana I would like to write something like this:

$user = ORM::factory('user')
    ->where('lower(email)', '=', strtolower('[email protected]'))
    ->find();

But this gives an error because ORM is trying to deduce the column name as 'lower(email)' rather than just 'email'.

I'm new to Kohana and ORM so alternatives that would give me the same result would be useful too.

+1  A: 

try this:

$user = ORM::factory('user')
    ->where(DB::expr('lower(email)'), '=', strtolower('[email protected]'))
    ->find();
antpaw
Worked perfectly, thank you.
Gerry
+2  A: 

Or IMHO even beter, try this:

$user = ORM::factory('user')
    ->where('LOWER("email")', '=', DB::expr("LOWER('[email protected]')"))
    ->find();

PS. I do not see any need to create a DB::lower() helper, but that might just be me...

EDIT:

$value = '[email protected]';

$user = ORM::factory('user')
    ->where('LOWER("email")', '= LOWER', (array) $value)
    ->find();

The query will become something like (havent used ORM in a while) "SELECT users.id, users.email FROM users WHERE LOWER("email") = LOWER ('[email protected]') LIMIT 1". Notice the space, I just updated some of my code to use this since I just figured out this posibility.

I hope you will be as happy with it as I am.

Darsstar
Use of helper was to make it cleaner when escaping the email to compare against. Imagine replacing '[email protected]' with $_POST['email'] and the code becomes uglier (or maybe I don't know how to make it look cleaner). Could you update your answer with an example on how to do that?
Gerry
Done, I do not know if an edit is enough to trigger a notify, so I just post this to be on the save side.
Darsstar
A: 

I'm not completely happy with the use of a helper but I use it a couple other classes so it's nice to keep the logic in one location. Here is what I'm currently using.

class DB extends Kohana_DB
{
    public static function lower($value)
    {
        return DB::expr('lower('.Database::instance()->quote($value).')');
    }
}

class Model_User extends Model_Base
{
    public static function find_by_email($email)
    {
        $user = ORM::factory('user')
            ->where(DB::expr('lower(email)'), '=', DB::lower($email))
            ->find();
        return $user;
    }
Gerry