【发布时间】:2018-03-16 10:52:41
【问题描述】:
我有一个用于显示数据的 gridView。 GridView 表有一个名为 Created By 的列,该列包含我从 user 表 获得的 User 的 ID强>。基本上,此列会将数据显示为 Integer(ID),如下所示:
但我设置了这样的代码来显示 ID 的 用户名:
[
'attribute' => 'created_by',
'format' => 'raw',
'value' => function ($data) {
$modelUser = Users::find()->where(['id' => $data->created_by])->one();
$nama = $modelUser->username;
return $nama;
},
'vAlign' => 'middle',
'hAlign' => 'center',
],
结果:
gridView 有过滤列,我正在尝试根据插入的值过滤数据。我正在尝试输入用户名作为过滤值,但它给出了错误消息“created By must be an Integer”,如下所示:
如何使用用户名(varchar)过滤该列?
谢谢
更新
这是我的 searchModel.php
<?php
namespace app\search;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Product;
/**
* ProductSearch represents the model behind the search form of `app\models\Product`.
*/
class ProductSearch extends Product {
/**
* @inheritdoc
*/
public function rules() {
return [
[['productId', 'userId', 'parentId', 'created_by'], 'integer'],
[['date', 'created_at', 'name', 'address'], 'safe'],
[['price'], 'number'],
];
}
/**
* @inheritdoc
*/
public function scenarios() {
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params) {
$query = Product::find();
// add conditions that should always apply here
$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
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'productId' => $this->productId,
'price' => $this->price,
'created_at' => $this->created_at,
'created_by' => $this->created_by,
]);
$query->andFilterWhere(['MONTH(date)' => $this->date])
->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'address', $this->address]);
return $dataProvider;
}
}
【问题讨论】:
标签: php search gridview filter yii2