How to get a node ID from a product display using the product ID
Extracting the product ID skus from an external source I had to update product display nodes linked to the product. Here's how I got it done:
First I needed the product ID. There are several ways of achieving this. You can query the database directly (the sku and the product ID can both be found in the 'commerce_product' table). Because chances are more actions must be performed on the product, it's better if we load it:
$product = commerce_product_load_by_sku($sku);
Now I can get the Product ID, which is needed for finding the Node ID of the Product Display Node ($product->product_id). With this I can perform an EntityFieldQuery. This is a query to fetch information from fields attached to entities. That's useful, because not everything can be found in the entity object itself.
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node', '=')
->propertyCondition('type', 'product_display')
->fieldCondition('field_product', 'product_id', $product->product_id, '=')
->range(0, 1);
if ($result = $query->execute()) {
//Do stuff with the result
}
That's all!
Hopefully this is useful information, I got the tip from Ryan Szrama (http://drupal.org/user/49344), thanks again!
Comments
Oops, small typo in the foreach statement:
<?php
function mymodule_get_referencing_node_id($product) {
// Itterate through all fields which refer to commerce products.
foreach (commerce_info_fields('commerce_product_reference') as $field) {
// Build query.
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node', '=')
->fieldCondition($field['field_name'], 'product_id', $product->product_id, '=')
->range(0, 1);
if ($result = $query->execute()) {
// Return node id.
return array_shift(array_keys($result['node']));
}
}
return false;
}
?>
Thank you! It works well!
Be careful with this function... you are actually forcing only one result and if the site is multilingual it means that your default language always comes first. Here's a revision that might help folks doing language stuff...
<?php
function mymodule_get_referencing_node_id($product) {
global $language;
// Itterate thhrough fields which refer to products.
foreach (commerce_info_fields('commerce_product_reference') as $field['field_name']) {
// Build query.
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node', '=')
->fieldCondition($field['field_name'], 'product_id', $product->product_id, '=')
->propertyCondition('language', $language->language, '=')
->range(0, 1);
if ($result = $query->execute()) {
// Return node id.
return array_shift(array_keys($result['node']));
}
}
return false;
}
?>
Cheers