marius
marius

Reputation: 1266

CakePHP contain condition cannot use variable?

I guess there is an easy solution for this issue, but i cant seem to find it out. I get back an error saying $p_name equals NULL on the contain Comments query. How is this possible since it was clearly set before.

$p_name = "Berta";

$query = $articles->find()->contain([
    'Comments' => function ($q) {
       return $q
            ->select(['name'])
            ->where(['Comments.name' => $p_name]);
    }
]);

Upvotes: 1

Views: 851

Answers (1)

Alex Stallen
Alex Stallen

Reputation: 2252

The variable is not available inside the scope of function q, you need to pass with the USE construct like:

$p_name = "Berta";

$query = $articles->find()->contain([
    'Comments' => function ($q) use ($p_name) {
       return $q
            ->select(['name'])
            ->where(['Comments.name' => $p_name]);
    }
]);

Upvotes: 3

Related Questions