我有这个问题:我需要从数据库中获取数据并过滤它们。但后来我需要使用自定义php函数来过滤那些过滤后的结果。
ActiveDataProvider中的Clasic搜索功能
public function search($params) {
$query = Passenger::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// I guess my function would go like here
Passenger::filterResultsEvenMore($dataProvider);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'passenger_id' => $this->passenger_id,
// ...
'version' => $this->version,
'status' => $this->status,
]);
return $dataProvider;
}
所以我的问题是如何处理dataProvider的结果,因为如果我对变量进行vardump看起来像这样,那里没有实际数据。
yii\data\ActiveDataProvider Object
(
[query] => common\models\PassengerQuery Object
(
[sql] =>
[on] =>
[joinWith] =>
[select] =>
[selectOption] =>
[distinct] =>
[from] =>
[groupBy] =>
[join] =>
[having] =>
[union] =>
[params] => Array()
[_events:yii\base\Component:private] => Array()
[_behaviors:yii\base\Component:private] => Array()
[where] => Array
(
[status] => 1
)
[limit] =>
[offset] =>
[orderBy] =>
[indexBy] =>
[emulateExecution] =>
[modelClass] => common\models\Passenger
[with] =>
[asArray] =>
[multiple] =>
[primaryModel] =>
[link] =>
[via] =>
[inverseOf] =>
)
[key] =>
[db] =>
[id] =>
[_sort:yii\data\BaseDataProvider:private] =>
[_pagination:yii\data\BaseDataProvider:private] =>
[_keys:yii\data\BaseDataProvider:private] =>
[_models:yii\data\BaseDataProvider:private] =>
[_totalCount:yii\data\BaseDataProvider:private] =>
[_events:yii\base\Component:private] => Array()
[_behaviors:yii\base\Component:private] =>
)
更新
我需要为每条记录使用这样的函数:
if (myFunction(table_column_1, table_column_2)) {
result_is_ok_return_it
} else {
do_not_return_this_record
}
答案 0 :(得分:1)
为什么不将其他过滤器添加到DataProvider中使用的查询对象?
您可以将条件解析为$query->andFilterWhere()
。如果你需要自定义函数,只需修改函数内的$dataProvider->query
对象。在数据提供程序中执行查询后,您只能通过手动筛选存储在$dataProvider->models
答案 1 :(得分:1)
答案 2 :(得分:0)
我想我遇到了一个解决方案,(看起来它正在运行)
http://www.yiiframework.com/doc-2.0/yii-data-basedataprovider.html#setModels()-detail
在我开始执行所有常规搜索内容之后,我会使用setModels()
函数执行此类操作
// ...
$filtered_models = [];
foreach ($dataProvider->models as $model) {
if ($model->status == 1) // example
$filtered_models[] = $model;
}
$dataProvider->setModels($filtered_models);
return $dataProvider;