How to manage and delete orphaned node references? I have a product node type and a review node type. The review node type has a node reference field that points to product. I can make one product and many users can add through using the node reference URL widget several reviews. I've been deleting the products while the reviews have been sitting orphaned in the database. This hasn't been a problem till I installed the Search API module. Perhaps the error being caused by the Entity module is a bug but those pesky node references have no business existing if the product has been erased or at least they shouldn't be published.

I can think of many solutions to this including never letting a product be deleted so that all content stays in the database till the end of time.

However, I would like to just delete all the reviews when a product is deleted. How do I do this.
This situation is exactly like deleting comments which are entities when deleting the node they are attached to. So I looked at the code in comment.module to see how it is handled there. Here is my solution:

/**
 * Implements hook_node_delete().
 */
function helper_node_delete($node) {
  if ($node-&gt;type == 'product'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' =&gt; $node-&gt;nid))-&gt;fetchCol();
    node_delete_multiple($nids);
  }
}


This also means that I can test to see if the node type is a review so all node types that reference the review can be handled too since hook_node_delete is recursive in this instance.