Active Record: The best way to display related records

I have published the question on StackOverflow:

I have two tables: record, user and a junction table record_user. I display the records, which are related to the logged user, using the Active Record.

In the model User I have the following functions:

public function getRecordUsers()


    return $this->hasMany(RecordUser::className(), ['user_id' => 'id']);


public function getRecords()


    return $this->hasMany(Record::className(), ['id' => 'record_id'])




In the model RecordSearch I define the query for the Active Data Provider:

public function search($params)


    // The Object with all records, to which has the user access (the id of the user is in the junction table record_user).

    $loggedUserRecords = YiiUser::findOne(Yii::$app->user->identity->id)->records;

    // From the object is extracted an array with ids.

    $loggedUserRecordsIds = yii\helpers\ArrayHelper::getColumn($loggedUserRecords, 'id');

    // The ids are used to filter the Record object.

    $query = Record::find()->filterWhere(['id' => $loggedUserRecordsIds]);

    $dataProvider = new ActiveDataProvider([

        'query' => $query,



The code works as expected. But I would like to know, if there is a more direct way to display the related records, without the extraction of ids from the object.


Follow this post: