Display random users photo and info on landing page

Hi I am a little new to Yii2 I would like to display 6 random users on my landing page, I have 2 tables profile and photo

profile table has the following structure
user_id
photo_id
name

photo table has
id
photo_id
source

would I need to run 2 different queries to display the username ‘name’ and photo?

something like this for the random photo

	    <?php $img_files = Yii::$app->db->createCommand('SELECT source FROM photo ORDER BY        RAND()LIMIT 1')->queryScalar(); 

$img_files = str_replace('\\', '/', $img_files);
$img_files1 = Yii::$app->db->createCommand('SELECT source FROM photo ORDER BY            RAND()LIMIT 1')->queryScalar(); 

$img_files1 = str_replace('\\', '/', $img_files1);
$img_files2 = Yii::$app->db->createCommand('SELECT source FROM photo ORDER BY        RAND()LIMIT 1')->queryScalar(); 

$img_files2 = str_replace('\\', '/', $img_files2);
$img_files3 = Yii::$app->db->createCommand('SELECT source FROM photo ORDER BY        RAND()LIMIT 1')->queryScalar(); 

 $img_files4 = str_replace('\\', '/', $img_files3);
 $img_files4 = Yii::$app->db->createCommand('SELECT source FROM photo ORDER BY        RAND()LIMIT 1')->queryScalar(); 

$img_files4 = str_replace('\\', '/', $img_files4);

 ?> 
<div class="profilescontainer">
<div class="uprofile"><img class="userLanding" src="/content/photos<?php  echo $img_files; ?> " alt="cool profile" width="200" height="200" /></div>
<div class="uprofile"><img class="userLanding" src="/content/photos<?php  echo $img_files1; ?> " alt="cool profile" width="200" height="200" /></div>
<div class="uprofile"><img class="userLanding" src="/content/photos<?php  echo $img_files2; ?> " alt="cool profile" width="200" height="200" /></div>
<div class="uprofile"><img class="userLanding" src="/content/photos<?php  echo $img_files3; ?> " alt="cool profile" width="200" height="200" /></div>
<div class="uprofile"><img class="userLanding" src="/content/photos<?php  echo $img_files4; ?> " alt="cool profile" width="200" height="200" /></div>

This works but its not the best method of doing it, any suggestions

  1. Don’t use db create commands. That’s just too complicated and no efficient. Use activerecord
$models = Photo::find()->orderBy(new Expression('rand()'))->limit(5)
  1. 5 tags? That’s too much work. Use a loop. Also what’s this raw html tag, use Html::img .
foreach($models as $model) {
    echo "<div>".Html::img($model->source)."</div>";
}
  • Do you mind if I turn this into a youtube video on my channel?

Thanks for the reply - I added you code above but got an error on page load, when I checked the logs I see

Error

Error: Class ‘Photo’ not found in /home/website.com/content/themes/coool/views/default/index.php:191