Skip to content

Instantly share code, notes, and snippets.

@adroitcode
Last active August 29, 2015 14:10
Show Gist options
  • Save adroitcode/c94414cee6ce87b07f13 to your computer and use it in GitHub Desktop.
Save adroitcode/c94414cee6ce87b07f13 to your computer and use it in GitHub Desktop.
Yii model to associative array with specified relations
//Put these two functions in your Controller.php
//and use like this:
//$department = Department::model->findBySql("SELECT * FROM department WHERE department_id=" . $department_id);
//$department_data = $this->get_model_associations($department,array('school'=>array('admins','pictureFile')),'students'=>array('pictureFile'));
//The first parameter is the model object, and the 2nd is an array of arrays of arrays and deep as you want to go.
//walk model detects if the current level is an associative array or just a regular array. If it is associative,
//it recursively gets the next layer of relations and then properly nests the data
function get_model_associations($model, array $attributes) {
$row = array();
foreach($model as $key => $value) {
$row[$key] = $value;
}
$row = $this->walk_model($model,$row,$attributes);
return $row;
}
function walk_model($model, array $row,array $model_names){
if($this->is_assoc($model_names)){
foreach($model_names as $nested_model_name => $nested_attributes) {
$name = trim($nested_model_name); //in case of spaces around commas
$model_values = $model->{$name};
//Check if the model association data is not null
if($model_values){
if(is_array($model_values)){
for($i = 0; $i < count($model_values); ++$i){
$this_model = $model_values[$i];
$row[$name][$i] = array();
foreach($this_model as $key => $value) {
$row[$name][$i][$key] = $value;
}
$row[$name][$i] = $this->walk_model($this_model,$row[$name][$i],$nested_attributes);
}
}else{
foreach($model_values as $key => $value) {
$row[$name][$key] = $value;
}
$row[$name] = $this->walk_model($model_values,$row[$name],$nested_attributes);
}
}else{
$relations = $model->relations();
$relation_type = $relations[$name][0];
if($relation_type == "CManyManyRelation" || $relation_type == "CHasManyRelation"){
$row[$name] = array();
}else{
$row[$name] = null;
}
}
}
}else{
foreach ($model_names as $attribute) {
$name = trim($attribute); //in case of spaces around commas
$model_data = $model->{$name};
//Check if the model association data is not null
if($model_data){
$row[$name] = array();
foreach($model_data as $key => $value) {
$row[$name][$key] = $value;
}
}else{
$relations = $model->relations();
$relation_type = $relations[$name][0];
if($relation_type == "CManyManyRelation" || $relation_type == "CHasManyRelation"){
$row[$name] = array();
}else{
$row[$name] = null;
}
}
}
}
//var_dump($row);
return $row;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment