2010-05-31 24 views
1

以下查詢從phpmyadmin運行時按預期返回一行。Kohana 3 - 查詢生成器給出0行

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

但是,當我嘗試做它的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); 

它打印

array(0) { }

我在做什麼錯?

回答

4

我不能立即說出查詢構建器有什麼問題,但是,爲了調試目的,請檢查此問題。

在您的db鏈上調用​​後,試試這個。

echo Database::instance()->last_query; 

這將在普通SQL中顯示上次執行的查詢。值得一看的是查詢生成器生成的內容,以及它與您在phpmyadmin中使用的SQL有何不同。

如果一切都失敗了,只需使用普通的查詢方法即可。

$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(); 
+0

echo Database :: instance() - > last_query;給我: SELECT'locations'。*,'units'。* FROM'units','locations' WHERE' units'.'location_id' ='locations.id'AND' units'.'id' ='1' 它看起來像bug應該是'locations'.'id'而不是'locations.id'??? 使用你所建議的普通查詢方法給了我以下錯誤: ErrorException [致命錯誤]:無法通過在線參考 傳遞參數2 「 - >綁定( ':身份證',(INT)$ ID)」 – pigfox 2010-06-01 00:56:56

+0

@ OK,嗯嘗試刪除轉換爲整數,或確保$ id設置在某處(可以在之後,因爲它是通過引用傳遞) – alex 2010-06-01 01:08:37

0

你會發現,你對last_query調用(在where部分)返回:

WHERE units.location_id = 'locations.id'傳遞比較值被引用爲字符串,因此查詢結果爲空。這可能會幫助你:http://kohanaframework.org/guide/api/DB#expr

至於你的致命錯誤,仔細檢查,以確保你顯式傳遞$ id(而不是另一個變量的引用副本),這就是我能想到考慮到你不提供任何來源。