2011-04-13 42 views
2

感謝Kohana的優秀文檔,我不得不訴諸於自己的SO。 ;)Kohana 3.1 ORM:How to make'where ... in'clause

希望這真的很簡單:我試圖收集屬於某組ID的所有故事。我的代碼如下:

$story_ids = '(12,56,99,213,319)'; 
$stories = ORM::factory('story')->where('id', 'IN', $story_ids)->find_all(); 

但是,這顯然不起作用。我收到一個MySQL錯誤消息,因爲查詢中的$story_ids字符串中存在單引號。

編輯:我也試過路過$story_ids作爲數組,但我只是得到一個「500內部服務器錯誤」

是否有可能做我問什麼?

在此先感謝。

回答

6

你也許忘記了- > select()

而且,這裏有兩種方法概述here用「IN」的文章:

ORM::factory('table1')->select('mls_id')->where('mls_id', 'NOT IN', DB::Select('mls_id')->from('table2'))->find_all(); 
ORM::factory('table1')->select('mls_id')->where('mls_id', 'NOT IN', DB::Expr('(SELECT mls_id FROM table2)'))->find_all(); 

我通常使用DB :: Expr的方法與你在做什麼。

+0

雖然我沒有執行子查詢。我已經有了字符串(或數組),並且只想將它傳遞給where方法的第三個參數。 如果我使用DB :: Expr(),它只是一個問題: ORM :: factory('story') - > where('id','IN',DB :: Expr($ story_ids) ) - > find_all();? – DondeEstaMiCulo 2011-04-13 00:41:38

+0

好,打我的屁股,打電話給我查理,它的工作! 將我的$ story_ids字符串包裝在DB :: Expr()中解決了這個問題。非常感謝! – DondeEstaMiCulo 2011-04-13 01:08:28

6

將$ story_ids作爲數組傳遞應該可行。

$story_ids = array(12,56,99,213,319); 
$stories = ORM::factory('story')->where('id', 'IN', $story_ids)->find_all(); 

你使用什麼Kohana版本?

+0

它在標題中,但我使用的是3.1.1,更具體。將值作爲數組傳遞返回500錯誤,正如我的描述中所述。 'DB :: Expr'完全適合我,所以我一直在使用它。 :) – DondeEstaMiCulo 2011-05-03 21:59:46

+0

@DondeEstaMiCulo奇怪這對我有用;) – veritas 2011-10-09 09:30:45