我遇到以下问题:我有一个用于客户的表,带有一个姓氏和名字。现在,我在数组中有可变关键字(在此示例中为硬编码2),我想检查其中一个关键字是否与名称或姓氏匹配。所以我想在以下代码片段中使用OR条件。不幸的是,它没有提供所需的输出:
$searchValueArr = ["keyword1","keyword2"];
$customers = $customersTable->find()
->where(function (QueryExpression $exp) {
$orConditions = $exp->or_(function ($or) {
foreach($searchValueArr as $searchValue) {
$or = $or
->eq('prename LIKE', "%".$searchValue."%")
->eq('name LIKE', "%".$searchValue."%");
}
return $or;
});
return $orConditions;
})
->all();
答案 0 :(得分:2)
您需要在每个匿名函数的$searchValueArr
部分列出use
,否则不在上下文中,例如:
$searchValueArr = ["keyword1","keyword2"];
$customers = $customersTable->find()
->where(function (QueryExpression $exp) use ($searchValueArr){
$orConditions = $exp->or_(function ($or) use ($searchValueArr){
foreach($searchValueArr as $searchValue) {
$or = $or
->eq('prename LIKE', "%".$searchValue."%")
->eq('name LIKE', "%".$searchValue."%");
}
return $or;
});
return $orConditions;
})
->all();
这确实是个人喜好,但是从技术上讲,您仍然可以对此类查询(或一组嵌套的OR)使用数组格式,例如:
$searchValueArr = ["keyword1","keyword2"];
$searchTerms = [];
foreach($searchValueArr as $searchValue) {
$searchTerms[] = [
'OR' => [
'prename LIKE' => "%".$searchValue."%",
'name LIKE' => "%".$searchValue."%"
]
];
}
$customers = $customersTable->find()
->where([
'OR' => $searchTerms
])
->all();