Yii2 model custom attributes

Hi everybody,

I have a model (ActiveRecord extended), named OUT_CONTACT. I want to add custom property, so i had a public getter function like :

    public function getAgentAccount() {

        $model_agent = Agents::find()->where(['Id' => $this->OrigQualOriginatorId])->one();

        if ($model_agent instanceof Agents) {

            return $model_agent->Account;


        return null;


I can access this custom property by : $model->AgentAccount, at this point all is ok.

But when i need to get a list of models , i query the model like this :

$models = OUT_CONTACTS::find()->where([ ... ])->all();

I would have directly in my model list the custom attribute/property, but i ve only attributes matching database fields…

Any help ?


Is it impossible to define a relation between OUT_CONTACT and Agents like the following?

public function getAgent()


    return $this->hasOne(Agents ::className(), ['id' => 'OrigQualOriginatorId']);


And then:

$model = OUT_CONTACT::find()->where(...)->one();

echo $model->agent->Account;

$models = OUT_CONTACT::find()->with('agent')->where(...)->all();

foreach($models as $model) {

   echo $model->agent->Account;


Yes it’s possible, but can i get directly Agent.Account when i will query OUT::Contacts like this ?

OUT_CONTACTS::find()->where([ ... ])->all();

You can consider using this approach.

Guide >> Active Record >> Selecting extra fields


But I think that using the relation is much more simple and effective in your case.

Thanks a lot :D