RedBeanPHP\AssociationManager::associate PHP Method

associate() public method

This method will associate two beans and store the connection between the two in a link table. Instead of two single beans this method also accepts two sets of beans. Returns the ID or the IDs of the linking beans.
public associate ( redbeanphp\OODBBean | array $beans1, redbeanphp\OODBBean | array $beans2 ) : array
$beans1 redbeanphp\OODBBean | array one or more beans to form the association
$beans2 redbeanphp\OODBBean | array one or more beans to form the association
return array
    public function associate($beans1, $beans2)
    {
        if (!is_array($beans1)) {
            $beans1 = array($beans1);
        }
        if (!is_array($beans2)) {
            $beans2 = array($beans2);
        }
        $results = array();
        foreach ($beans1 as $bean1) {
            foreach ($beans2 as $bean2) {
                $table = $this->getTable(array($bean1->getMeta('type'), $bean2->getMeta('type')));
                $bean = $this->oodb->dispense($table);
                $results[] = $this->associateBeans($bean1, $bean2, $bean);
            }
        }
        return count($results) > 1 ? $results : reset($results);
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * MySQL specific tests.
  *
  * @return void
  */
 public function testMySQL()
 {
     if ($this->currentlyActiveDriverID !== 'mysql') {
         return;
     }
     testpack('Throw exception in case of issue with assoc constraint');
     $bunny = R::dispense('bunny');
     $carrot = R::dispense('carrot');
     $faultyWriter = new \FaultyWriter(R::getToolBox()->getDatabaseAdapter());
     $faultyOODB = new OODB($faultyWriter);
     $faultyOODB->setBeanHelper(R::getRedBean()->getBeanHelper());
     $faultyToolbox = new ToolBox($faultyOODB, R::getToolBox()->getDatabaseAdapter(), $faultyWriter);
     $faultyAssociationManager = new AssociationManager($faultyToolbox);
     $faultyWriter->setSQLState('23000');
     $faultyAssociationManager->associate($bunny, $carrot);
     pass();
     $faultyWriter->setSQLState('42S22');
     R::nuke();
     try {
         $faultyAssociationManager->associate($bunny, $carrot);
         fail();
     } catch (SQL $exception) {
         pass();
     }
 }
All Usage Examples Of RedBeanPHP\AssociationManager::associate