You are here

修改其它模块的查询

让我们看一个hook_db_rewrite_sql()的具体实现。下面的例子利用了node表中moderate列来覆写节点查询。在我们修改了查询以后,那些不具有“管理内容”权限的用户,就会看不到处于待审核状态的节点(也就是,moderate列为1)。

 
/**
 * Implementation of hook_db_rewrite_sql().
 */
function moderate_db_rewrite_sql($query, $primary_table, $primary_field, $args) {
switch ($primary_field) {
case 'nid':
// Run only if the user does not already have full access.
if (!user_access('administer content')) {
$array = array();
if ($primary_table == 'n') {
// Node table is already present;
// just add a WHERE to hide moderated nodes.
$array['where'] = "(n.moderate = 0)";
}
// Test if node table is present but alias is not 'n'.
elseif (preg_match('@{node} ([A-Za-z_]+)@', $query, $match)) {
$node_table_alias = $match[1];
 
// Add a JOIN so that the moderate column will be available.
$array['join'] = "LEFT JOIN {node} n ON $node_table_alias.nid = n.nid";
 
// Add a WHERE to hide moderated nodes.
$array['where'] = "($node_table_alias.moderate = 0)";
}
return $array;
}
}
}
 
注意,我们检查所有查询,对于主键为nid的并且主表为node的查询,我们向里面插入一些额外信息。让我们看一下实际效果。
 
下面是最初的查询,未经moderate_db_rewrite_sql()处理的:
 
SELECT * FROM {node} n WHERE n.type = 'blog' and n.status = 1
 
下面是moderate_db_rewrite_sql()处理过后的查询:
 
SELECT * FROM {node} n WHERE n.type = 'blog' and n.status = 1 AND n.moderate = 0
 
moderate_db_rewrite_sql()被调用后,它向输入的查询中追加了AND n.moderate = 0。这个钩子通常还用于限制对节点、词汇表、术语、或者评论的访问。
db_rewrite_sql()局限于它能够理解的SQL语法。当你需要对表进行关联时,使用JOIN语法,而不是在FROM语句中对表进行关联。
 
下面的不正确:
 
SELECT * FROM {node} AS n, {comment} AS c WHERE n.nid = c.nid
 
这个正确:
 
SELECT * FROM {node} n INNER JOIN {comment} c ON n.nid = c.nid
 老葛的Drupal培训班 Think in Drupal

Drupal版本: