2010-07-01 27 views
2

我使用Postgres和Kohana 3的ORM模塊,並希望在執行比較之前使用postgres函數將已經在數據庫中的值轉換爲小寫字母。如何在Kohana中使用數據庫函數3 ORM select查詢

在SQL我會寫:

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

在Kohana中我想編寫這樣的事:

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

但是,這給出了一個錯誤,因爲ORM試圖推導出列名'降低(電子郵件)'而不僅僅是'電子郵件'。

我是Kohana和ORM的新手,所以可以給我提供相同結果的替代方案也很有用。

+1

警告:您將要替換DB函數('LOWER')與PHP的一個('strtolower') - 他們可能會或可能不會行爲相同的方式取決於多種因素(語言環境,編碼,性質輸入數據等)。 – 2010-07-01 22:40:01

+0

良好的調用,我添加了一個自定義的DB :: lower方法到我的應用程序,它轉義了傳入的值並將其包裝在較低的位置,因此我現在可以寫入: ... - > where(DB :: expr('lower (email)'),'=',DB :: lower($ email)) – 2010-07-01 23:33:18

回答

2

或者恕我直言,即使尤爲明顯,試試這個:

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

PS。我看不出有任何需要創建一個DB ::較低()輔助,但可能只是我...

編輯:

$value = '[email protected]'; 

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

查詢將成爲類似(還沒有使用ORM在)「SELECT users.id,users.email FROM users WHERE LOWER(」email「)= LOWER('[email protected]')LIMIT 1」。 注意這個空間,我只是更新了一些我的代碼來使用它,因爲我只是想出了這個可能性。

我希望你會像我一樣開心。

+0

幫助者的使用是爲了在轉義電子郵件時比較清晰。設想用$ _POST ['email']替換'[email protected]',代碼變得更醜陋(或者我不知道如何使它看起來更乾淨)。你能用一個例子來更新你的答案嗎? – 2010-07-02 20:24:00

+0

完成後,我不知道編輯是否足以觸發通知,因此我只是將其發佈到保存一側。 – Darsstar 2010-07-02 21:51:52

1

試試這個:

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

工作完美,謝謝。 – 2010-07-01 22:19:52

0

我對輔助工具的使用並不滿意,但是我使用了其他兩個類,所以將邏輯保存在一個位置是很好的。這是我目前使用的。

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; 
    } 
相關問題