How to pass a variable into a php callback with Yii2

Asked

Viewed 138 times

0

I am trying to make a somewhat abstract method that will execute a yii2 query depending on the attribute passed my code is:

public static function getModelosQuePodemTer($atributo) {
    self::$helper = $atributo;
    return self::find()
                ->joinWith(['modelo' => function($query) {
                        $query->andWhere([self::$helper => 1]);
                    }])
                ->all();

If I’m not mistaken I can not pass another attribute in the function being called, and I believe that my solution is a gambiarra

I wonder if there’s another way to do that

1 answer

1


You can use the use to access the variable $atributo within the scope of the function.

public static function getModelosQuePodemTer($atributo) {

    return self::find()
                ->joinWith(['modelo' => function($query)use($atributo) {
                        $query->andWhere([$atributo=> 1]);
                    }])
                ->all();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.