GApple is right, the format is correct, but there are couple of things that you might want to care about.
Delta Value
First you need to know the delta value of the latest node reference attached to $node_type_A
, the delta is actually a partial index, when combined with vid
field of the $node_type_A
, they become the index for node reference table in the database. In other words, its a count for $node_type_B
which are referenced in $node_type_A
, ok?
GApple is right again, you have to exactly say where to add the new reference. When you got that delta value you can exatcly say where to append (delta+1) the new reference. Here it is:
function get_current_delta($node_vid){
return db_result(db_query("SELECT delta FROM {content_field_type_A_node_ref}
WHERE vid = '%d'
ORDER BY delta DESC
LIMIT 1", $node_vid));
}
Adding the new reference
We got delta! so we can attach the new $node_type_B
node to our $node_type_A
node:
// Loading type_A node.
$node_type_A = node_load($some_nid);
// Getting current delta value.
$current_delta = get_current_delta($node_type_A->vid);
// "Appending" a node reference based on delta.
$node_type_A->field_type_B_node_ref = array($current_delta + 1 => array('nid' => $node_type_B_nid));
Resaving the updated node
Same old node_blah() story here, but after all that you need to call content_insert()
to make the node completely saved asidelong with its CCK fields:
// Resaving the updated node.
$node_type_A = node_submit($node_type_A);
node_save($node_type_A);
content_insert($node_type_A);
Flushing the content cache
Probably the most important part, this was killin' me for couple of days. CCK has a cache table in the database called cache_content
(take a look at its structure), after resaving the updated node, you will notice that nothing has changed in the $node_type_A
theme output eventhough that the tables are updated. We have to remove a record from that content cache table, this will force Drupal to show the latest snapshot of the data. You can define the following as a function:
db_query("DELETE FROM {cache_content} WHERE cid = '%s'", 'content:' . $node_type_A->nid . ':' . $node_type_A->vid);
Hope it helps ;)