Пример #1
0
 /**
  * Get an association.
  *
  * @param ActiveRecord $record
  *            A record.
  * @param array $association
  *            Association options.
  * @throws InvalidAssociationException If association type unknown.
  * @return ActiveCollection|ActiveRecord|null A collection, a record or null
  *         depending on association type.
  */
 public function getAssociation(ActiveRecord $record, $association)
 {
     switch ($association['type']) {
         case 'belongsTo':
             $key = $association['otherKey'];
             if (!isset($record->{$key})) {
                 return null;
             }
             $associated = $association['model']->find($record->{$key});
             if (!isset($associated)) {
                 // TODO: Orphan!! do something here ... following is only possible if
                 // key is nullable
                 // $record->$key = null;
                 // $record->save(false);
             }
             return $associated;
         case 'hasOne':
             $key = $association['thisKey'];
             $id = $this->primaryKey;
             return $association['model']->where($key . ' = ?', $record->{$id})->first();
         case 'hasMany':
         case 'hasAndBelongsToMany':
             $id = $this->primaryKey;
             $collection = new ActiveCollection($this, $record->{$id}, $association);
             $virtualData = $record->getVirtualData();
             if (isset($virtualData[$association['name'] . '_count'])) {
                 $collection->setCount($virtualData[$association['name'] . '_count']);
             }
             return $collection;
     }
     throw new InvalidAssociationException('Unknown association type: ' . $association['type']);
 }