我正在使用Yii2开发API REST应用程序,但我遇到以下查询问题:
我收到带有两个参数的url的get请求:
http://localhost/yii2/rest/web/index.php/v1/functions/search?name=test&code=int
我想在SQL查询中使用Or条件(而不是And条件)来处理get参数。
我知道使用这种方式有效:
$provider = new ActiveDataProvider([
'query' => $model->find()->select('idFunction')->where(['or',['name'=>'test'],['code'=>'int']]),
'pagination' => false
]);
但是这种方式无效。它表现为与条件:
$provider = new ActiveDataProvider([
'query' => $model->find()->select('idFunction')->where(['or',$params]),
'pagination' => false
]);
我认为它必须完成变量$params
转换的方式。
这是我的整个代码:
public function actionSearch()
{
$params = \Yii::$app->request->queryParams;
exit(print_r($params));
if (!empty($params)) {
$model = new $this->modelClass;
foreach ($params as $key => $value) {
if (!$model->hasAttribute($key)) {
throw new \yii\web\HttpException(404, 'Invalid attribute:' . $key);
}
}
try {
$provider = new ActiveDataProvider([
'query' => $model->find()->select('idFunction')->where(['or',$params]),
'pagination' => false
]);
} catch (Exception $ex) {
throw new \yii\web\HttpException(500, 'Internal server error');
}
if ($provider->getCount() <= 0) {
throw new \yii\web\HttpException(404, 'No entries found with this query string');
} else {
return $provider;
}
} else {
throw new \yii\web\HttpException(400, 'There are no query string');
}
}
使用array_unshift($conditions, 'or')
我在评论中建议的方式无效。该方法需要一个数组,其中每个元素(除了操作数本身之外)本身就是一个只有一个元素的数组。
我刚刚试过了一些可行的方法,但它不是很漂亮,它可以遍历元素并返回期望形式的数组。
$orQuery = ['or'];
foreach ($params as $key => $value) {
$orQuery[] = [$key => $value];
}
$query->where($orQuery);
这将返回该query()
方法期望的数组。
['or', ['name1' => 'value1'], ['name2' => 'value2'], ...]
产生SQL:
SELECT * FROM table WHERE ('name1'='value1') OR ('name2'='value2')...;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句