cancel
Showing results for 
Search instead for 
Did you mean: 

Check for existing association with PHP API

rob2020
Champ in-the-making
Champ in-the-making
Hi,

Can anyone advise how I can check to see if an association already exists (using PHP API)

I'm using code which works fine to add new associations ie

$contentNode->addAssociation($nodeToBeAddedToAssociation, "associationName");

But I'm not able to first see if that association already exists (in which case I'll skip it).  This will enable me to make my import script re-runnable.

Cheers

Rob
1 REPLY 1

rob2020
Champ in-the-making
Champ in-the-making
Hi,

In case it's useful for anyone, I figured this out I think - or at least one way of doing which seems to work OK. So I'll answer the question myself….

In the below example I have two existing references to documents.

$contentNode -> this is the document I'm working with (addiing associations, setting content etc)
$pluNode -> is another document elsewhere in the repo, which I already have a handle on.  I want to associate this $contentNode to $pluNode but that association may already exist (since I need a re-runnable script)

                                                               //have we already associated this document code
                        $already_associated = false;
                           $associations = $contentNode->getAssociations();
                           foreach ($associations as $assoc) {
                              $toNode = $assoc->getTo();
                              if ( $toNode->__toString() == $pluNode->__toString() )
                              {
                                 //echo $toNode->__toString() . ' : ' . $pluNode->__toString() . '<br />';
                                 $already_associated = true;
                              }
                           }
                           if ($already_associated == false) {
                              $contentNode->addAssociation($pluNode, "lush_productPluCodes");
                              $session->save();
                           }
                        else {
                           echo "this PLU is already associated: " . $plu;
                        }   
Improvements welcome.  Hope it's useful to someone.

Cheers

Rob