欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

views_query_alter apply “%LIKE%” condition

Is there a way in which I can alter the view query so I can get items that contain a specified string in title?

For example something like this:

if (isset($_GET['query']) && (!empty($_GET['query']))) {
    $view->query->add_where('title', $_GET['query'], 'LIKE');
}




正确答案


2down voteaccepted

You can do it using code similar to the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', $_GET['query'], 'LIKE');
  }
}

The first argument that is required from $query->add_where() is the group for the WHERE to add. The documentation says to pass 0 as argument, to use the default one.

The code I shown works if $_GET['query'] contains an SQL regular expression. If $_GET['query']contains a string that is not a regular expression, and that is used to build the regular expression for example as '%' . $_GET['query'] . '%', the code to use should be the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', '%' . db_like($_GET['query']) . '%', 'LIKE');
  }
}

Notice what reported in the documentation for views_plugin_query_default::add_where():

The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.


 
来自  http://drupal.stackexchange.com/questions/49397/views-query-alter-apply-like-condition
2down voteaccepted

You can do it using code similar to the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', $_GET['query'], 'LIKE');
  }
}

The first argument that is required from $query->add_where() is the group for the WHERE to add. The documentation says to pass 0 as argument, to use the default one.

The code I shown works if $_GET['query'] contains an SQL regular expression. If $_GET['query']contains a string that is not a regular expression, and that is used to build the regular expression for example as '%' . $_GET['query'] . '%', the code to use should be the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', '%' . db_like($_GET['query']) . '%', 'LIKE');
  }
}

Notice what reported in the documentation for views_plugin_query_default::add_where():

The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.


普通分类: