gpt4 book ai didi

search - Yii2 修改 Model search() 中的 find() 方法

转载 作者:行者123 更新时间:2023-12-02 08:11:02 28 4
gpt4 key购买 nike

我试图修改模型搜索中的 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;
}

这是我的 Controller 操作:

$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​​()方法?

谢谢。

最佳答案

我在这里看到两个错误:

  1. 您的查找方法

    $query = Group::find($accessGroups)

    不起作用 - 只需将其替换为

    $query = Group::find()->where(['id' => $accessGroups]);
  2. 我猜“必须设置数据提供程序属性”错误是由您的 View 代码引起的。例如。如果您使用 GridView,则应该设置其“dataProvider”小部件选项:

    GridView::widget([    'dataProvider' => $dataProviderMine,    'searchModel' => $searchModel,    'columns' => [        'id', 'status_id', 'created_date' // your view columns here    ]])
  3. 还可以考虑在搜索方法中使用子查询:

    $idAccessQuery = GroupAccess::find()    ->where(['user_id' => $userID, 'item_name' => 'group_creator'])    ->select('group_id');$query = Group::find()->where([    'id' => $idAccessQuery]);

关于search - Yii2 修改 Model search() 中的 find() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29718889/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com