MySQL 到 Drupal 7 db_select

MySQL to Drupal 7 db_select

我正在尝试使用 drupal 7 db_select 执行以下 mysql 查询。但我无法理解如何做到这一点。有谁能帮我把下面的 mysql 查询翻译成 drupal 7 动态数据库查询吗?

我的主要目标实际上是根据名称中给定的字符串位置对 mysql 结果进行排序。请记住,我不想获取所有结果并使用 php 对它们进行排序,而是我想使用 mysql 来做到这一点。据我所知,"ORDER BY LOCATE" 命令正是这样做的。

SELECT name FROM `taxonomy_term_data` WHERE LOCATE('credit', name) > 0 ORDER BY LOCATE('credit', name)

我认为你应该试试这样的方法。 db_like 函数似乎可以满足您的需求。

$result = db_select('taxonomy_term_data', 'ttd')
  ->fields('ttd', 'name')
  ->condition('ttd.name, '%' . db_like('credit') . '%', 'LIKE')
  ->orderBy('ttd.name', 'DESC')
  ->execute();

1。 db_select

的正确示例

这是可能的,使用 drupal 7 db_select,这是我的示例工作代码(在 this post 的帮助下完成)

我的示例中 table cities 包含列 city。查找具有双 "o" 的城市并按其位置排序:

$r = db_select('cities', 't')
  ->fields('t')
  ->condition('t.city', '%' . db_like('oo') . '%', 'LIKE');
$r->addExpression("LOCATE('oo', city) ", 'loc');
$r = $r->orderBy('loc', 'DESC')
  ->execute()
  ->fetchAllAssoc("id");

在您的示例中非常相似:

$r = db_select('taxonomy_term_data', 't')
  ->fields('t')
  ->condition('t.name', '%' . db_like('credit') . '%', 'LIKE');
$r->addExpression("LOCATE('credit', name) ", 'loc');
$r = $r->orderBy('loc', 'DESC'); //Or ASC
//Execute your query and gather result anyway you want.

2。您需要使用 db_select 吗?

正如有人在 link 的评论中所说,我发布了 "There are times and places to just use db_query."

我认为是时候了 :) 不要为了使用 drupal 方式的逻辑而使代码过于复杂,对于复杂的任务来说,这种逻辑通常已经过时或过于简单。