2012-07-03 47 views
2

使用DB查詢生成器在Kohana 3中構建交叉表更新的正確方法是什麼?Kohana 3使用查詢生成器進行交叉表更新

目前我只是使用DB :: expr,但我知道查詢生成器比這更聰明。

// update record 
$rows_updated = DB::update(DB::expr('user_list_permissions INNER JOIN users ON user_list_permissions.user_id = users.id')) 
->set($params) 
->where('user_list_permissions.id', '=', $user_list_permission_id) 
->where('users.account_id', '=', $this->account_id) 
->execute(); 

是的,當然我試圖用建立SELECT查詢時像「加盟」的方法,但我收到一個錯誤:

ErrorException [ 1 ]: Call to undefined method Database_Query_Builder_Update::join() 

回答

2

所以,你正在使用的表達做加盟,它可以在'on'函數中使用內置的'join'函數來實現這種行爲。

所以,在你的榜樣它看起來是這樣的:

$rows_updated = DB::update('user_list_permissions') 
->join('users','INNER') 
->on('user_list_permissions.user_id','=','users.id') 
->set($params) 
->where('user_list_permissions.id', '=', $user_list_permission_id) 
->where('users.account_id', '=', $this->account_id) 
->execute(); 

沒有太多就可以了但該文檔確實有在http://kohanaframework.org/3.2/guide/database/query/builder#joins

+0

不,不適用於更新。來自服務器的響應:ErrorException [1]:調用未定義的方法Database_Query_Builder_Update :: join() – JoshuaDavid

+0

從3.1開始,「join」方法是否添加到Database_Query_Builder_Update對象?我在v3.1.3.1(araea)中測試 – JoshuaDavid

+0

v.3.3.3在Database_Query_Builder_Update上沒有連接方法。 – Zoon

0

一點點這是一個老的文章,但只是爲了保持我在Kohana的經歷記錄。

如果你正在使用MySQL,它可以讓你進行跨表更新避免使用加入如下的:

UPDATE table1, table2 
SET table1.some_field = 'some_value' 
WHERE table1.foreign_key = table2.primary_key AND table2.other_field = 'other_value' 

注意條件table1.foreign_key = table2.primary_key是一樣的你在JOIN中使用ON子句。因此,您可以在Kohana中編寫一個交叉表更新,並遵循該模式避免JOIN:

$rows_updated = DB::update(DB::expr('user_list_permissions, users')) 
->set($params) 
->where('user_list_permissions.user_id', '=', DB::expr('users.id')) 
->where('user_list_permissions.id', '=', $user_list_permission_id) 
->where('users.account_id', '=', $this->account_id) 
->execute();