WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

Write your own sql to override the sql in your Drupal view

Submitted by barnettech on Fri, 12/18/2009 - 12:48

Here's a module that may do it http://drupal.org/project/views_modify_query, or use the code below:

Here is the module I wrote:
removedups_view.module is listed below

the query for the view news_events_rss is re-written prior to being executed. There were duplicate titles being listed so I used GROUP BY aggregator_item
_title to remove duplicates. The sql generated by the views module wasn't what was expected, so it had to go. I may make this into a module to submit to drupal.org. It is a module for developers like myself who found writing their own sql simpler, back during simpler times. This is a sql nostagia module. Retro.



<?php
function removedups_view_views_pre_execute(&$view) {
  watchdog('alert','tried to use views_pre_execute');
  if ($view->name \=\= 'news_events_rss') {
  //echo '
'; print_r($view->build_info['query']); echo '

';
$view->build_info['query'] = "SELECT aggregator_item.iid AS iid, aggregator_item.title AS aggregator_item_title, aggregator_item.link AS aggregator_item_link, aggregator_item.description AS aggregator_item_description, aggregator_item.timestamp AS aggregator_item_timestamp FROM aggregator_item aggregator_item LEFT JOIN aggregator_category_feed aggregator_category_feed ON aggregator_item.fid = aggregator_category_feed.fid LEFT JOIN aggregator_category aggregator_category ON aggregator_category_feed.cid = aggregator_category.cid WHERE aggregator_category.cid in ('%s') GROUP BY aggregator_item
_title ORDER BY aggregator_item_timestamp DESC";
//watchdog('alert','got here tried to use views_pre_execute');
}}

Note the ('%s') .... even though I ignore the views query builder in drupal, I still can use the variable set via the query builder! Very useful.

I just read a drupal planet article and the consultants did this differently: http://www.dynamiteheads.com/blog/jakub-suchy/optimizing-views-queries-…