Is there a single, unified method in Drupal 7 to get the last revision id for any given entity object? If so, what is that method?
3 Answers
I think entity_extract_ids()
is the quickest you'll get:
Helper function to extract id, vid, and bundle name from an entity.
e.g.
list($nid, $vid, $bundle) = entity_extract_ids('node', $some_node);
-
My issue with this is that it gives the next revision of an item. I'm looking for the last revision stored in the database. Commented Mar 17, 2014 at 17:00
-
That will give you the current revision ID, which by normal definition is the last in the database - what are you looking for if not the current revision?– Clive ♦Commented Mar 17, 2014 at 17:45
-
Well obvioulsy you're right :) I was doing something really dumb. Commented Mar 17, 2014 at 22:30
-
A minor clarification. When you call
entity_extract_ids
in hook_entity_update,$vid
will be equal to the new revision of the entity. So, while this answer is technically correct, you might be using logic inhook_entity_update
that acts as if the new entity revision id has not been determined yet, when in fact it already has. A better name forhook_entity_update
might behook_entity_updated
... Commented Aug 19, 2014 at 20:20
Calling {entity_type}_load for any entity will load the most recent version (caution - see comment below)
For example for a node calling node_load(1)
will load the most recent version of that node.
The revision id will be found in the vid property.
$node = node_load(1); // load the most recent version of node with id 1
$most_recent_version_id = $node->vid; // this is where you find the version id
Or for a user:
$user = user_load(1);
$most_recent_version_id = $user->vid; // this users version id
-
3This is not quite true node_load(1) will load the published version of the node. Which might not necessarily be the most recent. Commented Nov 7, 2016 at 15:46
-
1
$nid = 1;
$vid = db_query('SELECT vid FROM {node_revision} WHERE nid = :nid ORDER BY vid DESC LIMIT 0,1', array(':nid' => $nid))->fetchField();
$oNode = node_load($nid, $vid);
The above code will load the latest revision for NID 1 ($nid = 1, in this case) by finding the highest node_revision.vid. It then loads that revision into $oNode.
-
1Though this may be an answer to the question, please include some explanation of what the code does. Commented Mar 20, 2017 at 16:02