Yii到Yii2中的Search()函数

I'm new to the Yii framework and now I need to create a search function in Yii2. I already have found a search function in Yii which looks exactly like the funciton I need.


Here is the code:

public function searchDocuments($documentModel, $query, $content=false, $content_only=false) {

    $criteria = new CDbCriteria();
    $criteria->with = array(
        'tags' // Tabel tbl_tag toevoegen via de relations.
    );
    $criteria->compare('content', $query, true, "OR");
    $criteria->compare('description', $query, true, "OR");
    $criteria->compare('year', $query, true, "OR");
    $criteria->compare('title', $query, true, "OR");
    $criteria->compare('tags.slug', $query, true, "OR");
    $criteria->compare('title', $documentModel->title, true, "AND");
    $criteria->compare('description', $documentModel->description, true, "AND");
    $criteria->compare('tags.slug', $documentModel->tag_search, true, "AND");
    $criteria->compare('year', $documentModel->year, true, "AND");
    $criteria->compare('tags.state', 1 , false, "AND");
    $criteria->group = 't.id';

    $criteria->together = true;

    return new CActiveDataProvider( $documentModel, array(
            'pagination'=>array('pageSize'=>25),
            'criteria'  => $criteria,
            'sort'=>array(
                'attributes'=>array(
                    'tag_search'=>array(
                        'asc'=>'tags.slug',
                        'desc'=>'tags.slug DESC',
                    ),
                    '*',
                ),
            ),
        ) 
    );

} 
douruyun8153
douruyun8153 是的,我需要一个可以搜索多个模型并使用多个函数的搜索模型。
4 年多之前 回复
douhuijun3776
douhuijun3776 你想要yii2的搜索功能吗?
4 年多之前 回复

2个回答

Use Yii2 Gii to generate CRUD for your Model. Its generates ModelSearch model and its code contains good example of search code.

upd. Use model relations and $query->joinWith() method and filter by related table.

// model

public function getTags()
{
    return $this->hasMany(Tags::className(), ['id' => 'document_id']);
}

// search model 

public function search($params) 
{
    ...
    $query->joinWith(['tags' => function ($q) {
        $q->where('tags.slug LIKE "%' . $this->tag . '%"');
    }]);
    ...
}
duanming7961
duanming7961 谢谢,这就是我想要的
4 年多之前 回复

In your Model

public static function search($params)
{
    $query = self::find();
    $query->andWhere(['or','content',$params['content']]);
    $query->andWhere(['like','title',$params['title'].'%',false]);
    $query->with(['tags']);
    $query->groupBy('id');
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count(),'defaultPageSize'=>20]);
    $datas = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();
    return [
        'datas' => $datas,
        'pages' => $pages
    ];
}
dongzice4895
dongzice4895 更像是我有一个搜索模型,它搜索多个模型,而不仅仅是一个。
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问