Yii Framework Forum: Cactiverecord::getrelatedattribute Proposition - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Cactiverecord::getrelatedattribute Proposition

#1 User is offline   Chris83 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 440
  • Joined: 27-February 10
  • Location:Helsinki, Finland

Posted 13 March 2013 - 04:27 PM

Hello All,

We recently wrote a method for getting attributes through one or multiple active record relations. Maybe this would be something that could be considered to be added in some form in Yii2?

/**
 * Returns an attribute for the given relation.
 * @param string|array $through the relation(s).
 * @param string $attribute the attribute name.
 * @param string $defaultValue the default value to return if the relation is not found.
 * @return string the result.
 */
public function getRelatedAttribute($through,$attribute,$defaultValue='')
{
    if(!is_array($through))
        $through=array($through);
    $model=$this;
    foreach($through as $relation)
    {
        $model=$model->getRelated($relation);
        if($model===null)
            break;
    }
    return $model instanceof CActiveRecord && $model->hasAttribute($attribute)
            ? $model->getAttribute($attribute);
            : $defaultValue;
}

Best regards,
Chris

My contribution to the Yii community:
Account | Yiistrap | Auth | Bootstrap | NordCms | Rights | LESS | SEO | Img

Follow me:
Twitter | GitHub | Bitbucket
0

#2 User is offline   gbasto 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 70
  • Joined: 28-September 10
  • Location:Portugal

Posted 13 March 2013 - 05:35 PM

I don't see the difference/advantage of that method compared with: $model->getRelated($relation)->$attribute
0

#3 User is offline   Chris83 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 440
  • Joined: 27-February 10
  • Location:Helsinki, Finland

Posted 13 March 2013 - 05:55 PM

View Postgbasto, on 13 March 2013 - 05:35 PM, said:

I don't see the difference/advantage of that method compared with: $model->getRelated($relation)->$attribute

The difference is that you can use that method in e.g. views without checking if the relation actually exists and it won't crash if the relation isn't there.
Best regards,
Chris

My contribution to the Yii community:
Account | Yiistrap | Auth | Bootstrap | NordCms | Rights | LESS | SEO | Img

Follow me:
Twitter | GitHub | Bitbucket
1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users