2015-04-18 16 views
3

我试图修改模型搜索内部的find()方法,并引发错误“必须设置数据提供程序属性”。Yii2修改模型搜索()中的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​​()方法?

谢谢。

回答

2

我在这里看到的两个错误:

  1. 你find方法

    $query = Group::find($accessGroups)

    将无法​​正常工作 - 只是

    $query = Group::find()->where(['id' => $accessGroups]);
  2. 我猜“的数据提供属性替换必须设置“错误是由您的视图代码造成的。例如。如果你正在使用的GridView,你应该设置它的“数据提供程序”窗口小部件选项:

    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 
    ]);
+0

所以,子查询消除需要foreach循环吗?此外,idAccesQuery可能会返回多个ID。这对Group :: find'id'=> array()是一个问题吗?谢谢! –

+0

正确。这将通过你的GroupAccess数据库表中的多个group_id选择,为你的sql添加一个子查询。注意,不会有额外的请求do db - 全部在一个查询中。 –

+0

是否还有两个数据库查询,一个用于访问表,另一个用于组? –