drfu80954 2017-01-30 09:37
浏览 504
已采纳

如何在Yii2搜索模型中使用数组进行搜索

public function actionIndex()
{
    $searchModel = new SubjectSearch();
    $searchModel->search()->query->andFilterWhere(['in','subjectID',[1,2,3]]);
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

I've tried different ways like

$searchModel->subjectID = [1,2,3]

$searchModel->search()->query->andFilterWhere(['in','subjectID',[1,2,3]]);

But they doesn't work for me.

Actually, ArrayDataprovider might seem to be a better solution in this case, but Array Dataprovide won't work with filters.

BTW, the real question is to search with ManyToMany Relationship.

many Users to many Groups.
many Groups to many Subjects.

UserGroupTbl contains UserID and GroupID
SubjectGroup contains SubjectID and GroupID

I'm trying to do that with:

$groups = $appUser->getGroups();
$subjectIDs = [];
foreach ($groups as $group) {
    $subjectIDs[] = $group->getSubjectIDs
}
$searchModel = new SubjectSearch();
$searchModel->subjectID = $subjectIDs;

But that doesn't work and is certainly not a good method

Please help me a little bit with it.

================Update==============

    $searchModel = new SubjectSearch();
    $searchModel->subjectID = [1,2];
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

Result in "Array to string conversion" error.

    $searchModel = new SubjectSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->query->andFilterWhere(['in','subjectID',[1,2]]);;

This method actually worked. BTW, do you have a little bit advice about handling many to many searching?

  • 写回答

3条回答 默认 最新

  • doulang6013 2017-01-30 10:11
    关注

    Each time you call search you will get a new query object so you can't add parameters to it, use this method:

    $searchModel = new SubjectSearch();
    $searchModel->subjectID = [1,2,3];
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    

    In the SubjectSearch model you should have this in the search function:

    $query->andFilterWhere(
       [
          ...
          'subjectId' => $this->subjectID,
          ...
       ]
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?