Hi.
Need a hint from Yii2 experts.
1)there are two models post and category,connected via many to many relation. i want in grid view of post to be able to type, for example, 2 names of categories, comma separated, and search result must include all posts that have both this categories.
here is the code:
[ 'label'=>'Categories attached',
'attribute'=>'category_id'//contains an array,
'value'=>function ($model) {
$arr = ArrayHelper::getColumn($model->category_id,'name');
$str = implode(',',$arr);
return $str;
},
'filter' =>?what must go here?'<input class="form-control" name="category_id" type="text" placeholder="Names comma separated">'-i use this for now,but i have been stuck in search rules. in my Post Search model Ihave the $params['category_id'] value but after $this->load($params);$this does not contain such attr.
]
i think i need to create some special search rules, because simple:
$query->andFilterWhere(['like','category_id',$this->category_id]);
does not work, as category_id is an array…
i was working on this and for now i have part of solution, i would like to present it here:
public function search($params)
{
$query = Post::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query = Category::find();
$c = explode(',', $params['category_id']);
$query->select('id')->where(['or like', 'name', $c]);
//var_dump($query->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql);
$q = $query->all();
$arr = [];
foreach ($q as $key => $value) {
$arr[] = $value['attributes']['id'];
}
$query = Post::find();
if(!empty($arr)) {
$q = $query->select(['pc.id'])
->from('post pc');
$i = 0;
foreach ($arr as $a) {
$alias = "p" . $i;
$q->join('INNER JOIN', 'post_cat ' . $alias, $alias . '.post_id=pc.id')->andWhere([$alias . '.category_id' => $a]);
$i++;
}
$f = $q->all();
$arr = [];
foreach ($f as $key => $value) {
$arr[] = $value['attributes']['id'];
}
}
$query->andFilterWhere([
'id' => $this->id,
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'content', $this->content]);
//->andFilterWhere(['in','id',$arr]);
return $dataProvider;
}
}
queries work fine, i var_dumped each of them, but nothing happends at all in my grid view, also other columns filter stop working. i think using another model crushes smth, may some one can give a hint of what is going on here. may be i nee to create separate function out of search()? i will keep working on it
2)second issue is that when i try to filter id column i always get this bug
"strtr() expects parameter 1 to be string, object given", what is the solution for this?may be someone had same problem?