How to pass a variable in joinWith

Hi all, i have many days searching for an answer for this question on the internet, so i hope you could help in this.

All i want is to make some easy query, i put you an example:

Model A Have a “HasMany” relation with model B, the relation is ‘profile’, for example.

In my code, i need to do something like this…




$varName = $modelC->name;


$user = ModelA::find()->joinWith(['profile' => function($query){

      $query->andFilterWhere(['ModelB.name' => $varName]);

}])->orderBy($modelA->date DESC)->all();



I think this could be easy, but yii2 throw me an exception every time i tried to use a variable in my method inside de function($query).

I tried to pass that variable to the function, but throw me an error again.

Is there a way to do this??

http://php.net/manual/en/functions.anonymous.php#example-197




$varName = $modelC->name;


$user = ModelA::find()->joinWith(['profile' => function($query) (use $varName){

      $query->andFilterWhere(['ModelB.name' => $varName]);

}])->orderBy($modelA->date DESC)->all();



Rolf i used that on gridviews and never tried to use it there, thanks a lot!!