[Solved] Using Variable As Parameter In Query Builder Function

In my view action, I have a Query Builder function with parameter binding; like so:




public function actionView($slug)

{

    $books = Post::find()

        ->joinWith(['tags' => function($query) {

            $query->where('tags.slug = :slug');

            $query->params(':slug' => $slug);

        }])

    ->where('status = :status', ['status' => 1]);

    ...

}



However, I can’t use the $slug variable as in the parameter binding. Error returned was “Undefined variable: slug”. How can I use that variable in Query Builder function?

not sure but I would start with this, i think it should be an array




$query->params([':slug' => $slug]);



what about this


public function actionView($slug)

{

    $books = Post::find()

        ->joinWith(['tags' => function($query) {

            $query->where(['tags.slug' => $slug]); 

        }])

    ->andWhere(['status' =>1]);

    ...

}


$books = Post::find()

        ->joinWith(['tags' => function($query) use($slug) {

            $query->where('tags.slug = :slug');

            $query->params([':slug' => $slug]);

        }])

    ->where('status = :status', ['status' => 1]);

Thanks for pointing that out. :)

Does not work, the ‘$slug’ variable must be passed to the query function. Reply below solves it.

This solves it. Thank you very much! :)