Is it okay to perform an ActiveRecord find() query on a view?

On my view index, I have a ListView widget that renders all record from an Article table.

Then on the itemView of the ListView widget, I have a foreach loop that finds 5 image of each article. Code as per below:-




foreach (Image::find()->where('id != :id', ['id'=>$model->id])->limit(5) as $image)

{

    echo Html::img(Html::encode($image->thumbnail));

}

Pretty crude and I read that it is generally not recommended to perform any find operation on a view. Is there any alternative to this?

you can declare a simple one to many association you can read on relational queries here

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#working-with-relational-data

I generally prefer handling all database operations within my models. It’s cleaner, and allows easier testing. So for instance, within the Article model, I’d just declare a function such as:


public function getImages($limit = 5, $offset = 0) 

{

    // Relation here to retrieve and return images

}

And then within the view:


foreach ($model->getImages(5) as $image): ?>

    <!-- render the image !-->

<?php endforeach; ?>