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',
),
'*',
),
),
)
);
}
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 . '%"');
}]);
...
}
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
];
}