CAKEPHP包含条件不能使用变量



我想对于这个问题有一个简单的解决方案,但我似乎找不到它。我会回到一个错误,说$ p_name等于包含注释查询的null。这是怎么可能的,因为它是在明确设置的。

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

该变量在函数Q的范围内不可用,您需要通过使用构造来传递:

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

最新更新