我對Drupal非常陌生,嘗試構建一個模塊,該模塊允許管理員使用關鍵字標記節點以將節點提升到搜索結果頂部。在Drupal 7中更改數據集的搜索查詢條件
我有一個單獨的數據庫表的關鍵字和各自的節點ID。此表是聯合在一起通過hook_query_alter的search_index表...
function mos_search_result_forcer_query_alter(QueryAlterableInterface &$query) {
if (get_class($query) !== 'PagerDefault') { //<< check this because this function will mod all queries elsewise
return;
}
// create unioned search index result set...
$index = db_select('search_index', 's');
$index->addField('s', 'sid');
$index->addField('s', 'word');
$index->addField('s', 'score');
$index->addField('s', 'type');
$msrfi = db_select('mos_search_result_forcer', 'm');
$msrfi->addField('m', 'nid', 'sid');
$msrfi->addField('m', 'keyword', 'word');
$msrfi->addExpression('(SELECT MAX(score) + m.id/(SELECT MAX(id) FROM {mos_search_result_forcer}) FROM {search_index})', 'score');
$msrfi->addExpression(':type', 'type', array(':type' => 'node'));
$index->union($msrfi);
$tables =& $query->getTables();
$tables['i']['table'] = $index;
return $query;
}
的Drupal然後生成幾乎正確的查詢......
SELECT
i.type AS type, i.sid AS sid, SUM(CAST('10' AS DECIMAL) * COALESCE(((12.048628015788 * i.score * t.count)), 0)/CAST('10' AS DECIMAL)) AS calculated_score
FROM (
SELECT
s.sid AS sid, s.word AS word, s.score AS score, s.type AS type
FROM
search_index s
UNION SELECT
m.nid AS sid, m.keyword AS word, (
SELECT
MAX(score) + m.id/(SELECT MAX(id) FROM mos_search_result_forcer)
FROM
search_index
) AS score, 'node' AS type
FROM
mos_search_result_forcer m
) i
INNER JOIN node n ON n.nid = i.sid
INNER JOIN search_total t ON i.word = t.word
INNER JOIN search_dataset d ON i.sid = d.sid AND i.type = d.type
WHERE (n.status = '1')
AND((i.word = 'turtles'))
AND (i.type = 'node')
/* this is the problem line... */
AND((d.data LIKE '% turtles %' ESCAPE '\\'))
/* ...end problem line */
GROUP BY i.type, i.sid
HAVING (COUNT(*) >= '1')
ORDER BY calculated_score DESC
LIMIT 10 OFFSET 0
...我需要的是 「問題行」 到閱讀...
AND((d.data LIKE '% turtles %' ESCAPE '\\') OR (d.sid IN (SELECT nid FROM mos_search_result_forcer)))
...我可以使用什麼鉤子來添加該OR條件?
- 我不想破解Drupal的核心。
- 我不想更改聯合/子查詢(不是我的決定)。
- 我會稍後優化查詢 - 功能更重要。
謝謝,聰明的人!
謝謝!該代碼實際上與我正在試驗的代碼非常相似;然而,問題在於,在調用hook_query_alter之後,我需要修改的條件被添加到查詢對象*中。我希望在調用查詢的execute方法之前可能會有另一個鉤子被調用,或者在查詢對象向其本身添加條件之前調用正確的鉤子? – chaseisabelle 2014-09-15 14:05:55
這很不可能(實際上我認爲不可能)在'hook_query_alter()'之後查詢被改變......可能發生的另一個模塊也實現了'hook_query_alter()',它的實現只是在你的後面運行。你可以通過實現['hook_module_implements_alter()'](https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_module_implements_alter/7)並移動你的模塊的' hook_query_alter()'鉤到列表的末尾 – Clive 2014-09-15 14:09:58
再次謝謝你!當var_dumping查詢對象時,我能夠看到條件。查詢arg(傳遞給'hook_query_alter')的類型是'PagerDefault',它具有'SearchQuery'類型的受保護屬性'$ query'。受保護的'SearchQuery'屬性具有我需要修改的條件數組。有沒有辦法可以修改這樣的嵌套查詢條件? – chaseisabelle 2014-09-15 15:06:32