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条)

报告相同问题?

悬赏问题

  • ¥15 找一个QT页面+目标识别(行人检测)的开源项目
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错
  • ¥15 如何让子窗口鼠标滚动独立,不要传递消息给主窗口