From 90839ceb5d5eb1796cff125011af16ee507f60c7 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Sun, 3 Nov 2013 02:08:26 +0100 Subject: [PATCH] Proposal for accessing populated relations fixes #842 - allows checking whether a relation has been populated - getting a list of relation names that have been populated - getting all populated relation data todo: - [] add phpdoc --- framework/yii/db/ActiveRecord.php | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/framework/yii/db/ActiveRecord.php b/framework/yii/db/ActiveRecord.php index 154d7ac..cb99b9f 100644 --- a/framework/yii/db/ActiveRecord.php +++ b/framework/yii/db/ActiveRecord.php @@ -532,6 +532,45 @@ class ActiveRecord extends Model } /** + * Check whether the named relation has been populated with records. + * @param string $name the relation name (case-insensitive) + * @return bool whether relation has been populated with records. + */ + public function isRelationPopulated($name) + { + return array_key_exists(strtolower($name), $this->_related); + } + + /** + * @return array list of populated relation names + */ + public function getPopulatedRelationNames() + { + $relations = array_keys($this->_related); + $reflection = new \ReflectionClass($this); + foreach($relations as $i => $relation) { + if ($reflection->hasMethod('get' . $relation)) { + $method = $reflection->getMethod('get' . $relation); + $relations[$i] = lcfirst(substr($method->name, 3)); + } + } + return $relations; + } + + /** + * @return array all populated relations + */ + public function getPopulatedRelations() + { + $relations = $this->getPopulatedRelationNames(); + $data = []; + foreach($relations as $name) { + $data[$name] = $this->_related[strtolower($name)]; + } + return $data; + } + + /** * Returns the list of all attribute names of the model. * The default implementation will return all column names of the table associated with this AR class. * @return array list of attribute names.