2

使用 DB 查询构建器在 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();

是的,当然我尝试使用“join”方法,就像在构建 SELECT 查询时一样,但是我收到一个错误:

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

2 回答 2

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上确实有一点

于 2012-07-04T07:49:00.807 回答
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();
于 2016-09-17T16:43:12.173 回答