Profile picture for user admin
Daniel Sipos
08 Sep 2014

Have you ever needed to remove in bulk a bunch of voting results for, let's say, a given content type? There is no option in the UI but you can find in the votingapi.module some handy functions that will allow you to write a customized update hook.

So let's say that we need to remove all the results for the article content type. If we look in the votingapi_vote table, we don't see any bundle or content type column, but we see an entity_id. So we need to get all the ids of our article nodes:

$query = db_query("SELECT nid FROM node WHERE type = 'article'");
foreach ($query as $res) {
  $nids[] = $res->nid;
}

Now we have the $nids array containing all of our node IDs. Next, let's load all the votes for these IDs:

module_load_include('module', 'votingapi', 'votingapi.module');
$votes = votingapi_select_votes(array('entity_id' => $nids));

First we include the right module file and then we use one of its functions to select all the votes that match some criteria (in our case an array of IDs). Next, we need to worry also about the votingapi_cache table which contains the results of the voting per entity. We need to remove that as well. So we'll use another helper function from Voting API:

$results = votingapi_select_results(array('entity_id' => $nids));

Now we have also the result objects we need to delete so we can proceed with the actual removal. For this, we can use two more handy methods from the Voting API module:

votingapi_delete_votes($votes);
votingapi_delete_results($results);

And that's it. This will remove all the votes and their aggregated results from both tables. It may take some time so make sure you have enough server resources to perform this task.

To use this code, I recommend creating an update hook in a custom module that you run once. But make sure you properly test it on your test environment before deploying and running the code on production servers. Always keep in mind the possibility of the server running out of resources depending on how many votes you have in the database.

Do you have any better way of batch deleting votes/results? This is what I found and I'm curious if you know of any better ways. Let me know.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Add new comment