Model function not working

Can someone please tell what I am doing that is soooo wrong.

I have

public function getClientDriversDatalist()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_HTML;

$output = '';
if (($modelDrivers = $this->hasMany(ClientsDrivers::class, ['ClientId' => 'ClientId'])) !== null) {
    foreach($modelDrivers as $key => $modelDriver){
        $output .= $key; // . '~' . $modelDriver->ClientId;
    }
}
return $output;

}

When I echo the result I get

sql
on
joinWith
select
selectOption
distinct
from
groupBy
join
having
union
withQueries
params
queryCacheDuration
queryCacheDependency
where
limit
offset
orderBy
indexBy
emulateExecution
modelClass
with
asArray
multiple
primaryModel
link
via
inverseOf

I just don’t get what is going on. It should return 2 $models, yet it seems to iterate 29 times? There is only a single Client on the form and only 2 records in the ClientsDrivers table.

I’ve switch to using

$modelDrivers = ClientsDrivers::find()
	->where(['ClientId' => $this->ClientId])
	->orderBy(['FirstName' => SORT_ASC, 'LastName' => SORT_ASC])
	->all();

and it works, I just don’t understand why my original version didn’t

hasMany returns an instance of ActiveQueryInterface (ActiveQuery in most cases). But I understand your confusion. It works like that:

When you declare relation i.e. named orders you write it like that:

public function getOrders()
{
    return $this->hasMany('order', ['invoice_id' => 'id']);
}

Now, when you call it like that:

$model->getOrders()

the result is an instance of ActiveQuery so you can use it for additional stuff like i.e.:

$model->getOrders()->count()

BUT when you call like that:

$model->orders

it actually is fetching the models using the configured relation and you get actual models then. hasOne() works the same way.

1 Like