我正在尝试修改模型搜索中的find()方法并抛出错误"必须设置数据提供者属性"。
这是我的搜索模型:
public function search($params)
{
$userID = Yii::$app->user->identity->id;
$groups = GroupAccess::find()
->where(['user_id' => $userID, 'item_name' => 'group_creator'])
->asArray()
->all();
foreach ($groups as $group) {
$accessGroups[] = $group['group_id'];
}
$query = Group::find($accessGroups);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'status_id' => $this->status_id,
//'created_user_id' => $this->created_user_id,
'created_date' => $this->created_date,
'profile_updated_user_id' => $this->profile_updated_user_id,
'profile_updated_date' => $this->profile_updated_date,
'last_accessed_user_id' => $this->last_accessed_user_id,
'last_accessed_date' => $this->last_accessed_date,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
}
这是我的控制器动作:
$searchModel = new GroupSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if (Yii::$app->request->isPjax) {
return $this->renderAjax('groups', [
'searchModel' => $searchModel,
'dataProviderMine' => $dataProvider,
]);
} else {
return $this->render('groups', [
'searchModel' => $searchModel,
'dataProviderMine' => $dataProvider,
]);
}
}
优化查询非常重要,因为用户应该能够看到其他组。
如何正确修改find()方法?
感谢。
答案 0 :(得分:2)
我在这里看到两个错误:
您的查找方法
$query = Group::find($accessGroups)
无效 - 只需将其替换为
即可$query = Group::find()->where(['id' => $accessGroups]);
我想"必须设置数据提供者属性"错误是由您的视图代码引起的。例如。如果您使用的是GridView,则应设置其“数据提供者”。小部件选项:
GridView::widget([ 'dataProvider' => $dataProviderMine, 'searchModel' => $searchModel, 'columns' => [ 'id', 'status_id', 'created_date' // your view columns here ] ])
还要考虑在搜索方法中使用子查询:
$idAccessQuery = GroupAccess::find() ->where(['user_id' => $userID, 'item_name' => 'group_creator']) ->select('group_id'); $query = Group::find()->where([ 'id' => $idAccessQuery ]);