具有条件db_or等的Drupal 7 DB API查询

时间:2015-05-08 16:34:59

标签: mysql drupal drupal-7

我在使用drql 7中的sql查询时遇到了一些问题。 基本上,我想知道我的db_api的drupal代码是否适用于我希望它生成的SQL查询。

请参阅以下代码:

/*
  SQL Query
  Note: The the 'a' in '%a%', is just a sample of some text input by a user. 
*/

SELECT u.uid, fn.field_first_name_value, ln.field_last_name_value 
FROM role r
JOIN users_roles ur ON (r.rid = ur.rid)
JOIN users u ON (u.uid = ur.uid)
JOIN field_data_field_first_name fn ON (fn.entity_id = u.uid)
JOIN field_data_field_last_name ln ON (ln.entity_id = u.uid)
WHERE (fn.field_first_name_value LIKE '%a%' OR ln.field_last_name_value LIKE '%a')
AND r.name = 'custom_role'
LIMIT 0, 5


/*
   DRUPAL 7 DB API CODE
 */

$name = $_POST['name'];
$res = db_select('role', 'r');

$res->join('users_roles', 'ur', 'ur.rid = r.rid');
$res->join('users', 'u', 'u.uid = ur.uid');
$res->join('field_data_field_first_name', 'fn', 'fn.entity_id = u.uid');
$res->join('field_data_field_last_name', 'ln', 'ln.entity_id = u.uid');

$res->fields('u', array('uid'));
$res->fields('fn', array('field_first_name_value'));
$res->fields('ln', array('field_last_name_value'));                        

$or = db_or()->condition('fn.field_first_name_value', '%'.db_like($name).'%', 'LIKE');
$or->condition('ln.field_first_name_value', '%'.db_like($name).'%', 'LIKE');

$res->condition($or)->condition('r.name', 'custom_role', '=');
$res->range(0,5);            

$res->execute();

另外,如果有方法可以通过db api看到生成的sql,那么这对于调试来说非常有用。 感谢。

1 个答案:

答案 0 :(得分:2)

我无法执行它,因为我没有像你一样的表,但生成的查询看起来不错。

SELECT u.uid AS uid, fn.field_first_name_value AS field_first_name_value, ln.field_last_name_value AS field_last_name_value
FROM
{role} r
INNER JOIN {users_roles} ur ON ur.rid = r.rid
INNER JOIN {users} u ON u.uid = ur.uid
INNER JOIN {field_data_field_first_name} fn ON fn.entity_id = u.uid
INNER JOIN {field_data_field_last_name} ln ON ln.entity_id = u.uid
WHERE ( (fn.field_first_name_value LIKE :db_condition_placeholder_0 ESCAPE '\\') OR (ln.field_first_name_value LIKE :db_condition_placeholder_1 ESCAPE '\\') )AND (r.name = :db_condition_placeholder_2)
LIMIT 5 OFFSET 0

如果您想自己打印查询,可以使用

print $res->__toString() . "\n\n";
var_export($res->getArguments());

watchdog('MY_QUERY_DEBUG', $res->__toString(), $res->getArguments());

将其添加到监视程序日志中。