How to include relation of relation in find model

Hi,I have the next database extructure, I need to validate if the user that search the reservation its member of the agency that insert the row. I have the model of the three tables

Reservation model with @property User $employee and user_id column

User model with @property Agency $agency and agency_id column

Agency model

I try to find a model database with the next code:

$attributes = array(

        'userId' => Yii::$app->user->getId(), // AND agency.operator_id=:userId


        'reservationId' => $keyReservation,


    );


    $model = Reservation::find()->with('employee', 'employee.agency')->where('id=:reservationId AND agency.operator_id=:userId', $attributes)->all();

But system show my next error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘agency.operator_id’ in ‘where clause’

The SQL being executed was: SELECT * FROM reservation WHERE id=‘31325’ AND agency.operator_id=1

Error Info: Array

(

[0] => 42S22


[1] => 1054


[2] => Unknown column 'agency.operator_id' in 'where clause'

)

Caused by: PDOException

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘agency.operator_id’ in ‘where clause’

I understand the error, but I dont know how I do to implement the with operation with a third relation table.

I found my error, and find that you dont must to use with() function if need validate relation conditions. Prefer use joinWith():

$model = Reservation::find()

->joinWith([‘employee’, ‘employee.agency’])

->where([‘reservation.id’ => $id])

->andWhere([‘agency.operator_id’ => $employee->agency_id])

->one();

 ->with('firstRelation.secondRelation')
1 Like