Mysql Yii2 SearchModel查询-将整数值映射到字符串
我正在努力实现的目标: 我有一个带有Mysql Yii2 SearchModel查询-将整数值映射到字符串,mysql,sql,yii2,Mysql,Sql,Yii2,我正在努力实现的目标: 我有一个带有类型字段的表,该字段保存整数值。这些整数值表示不同的字符串 我希望能够使用整数表示的字符串值搜索表 例如type=abc而不是type=0 我试过什么: 我已经为模型创建了一个查询类,并尝试使用$boolean\u map属性: class ReportQuery extends FilterableQuery { protected $filterable = [ 'type' => 'LIKE', 'remov
类型
字段的表,该字段保存整数值。这些整数值表示不同的字符串
我希望能够使用整数表示的字符串值搜索表
例如type=abc
而不是type=0
我试过什么:
我已经为模型创建了一个查询类,并尝试使用$boolean\u map
属性:
class ReportQuery extends FilterableQuery
{
protected $filterable = [
'type' => 'LIKE',
'removed_the_rest'
];
protected $boolean_map = ["type" => [ 'addacs' => 0, "arudd" => 1,]];
}
然后我重写了模型的find
方法以使用查询类:
public static function find()
{
$query = new ReportQuery(get_called_class());
return $query;
}
在搜索模型中,我有:
public function search($params)
{
$query = Report::find();
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
$this->load($params, '');
if (!$this->validate()) {
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->type,
]);
$query->andFilterWhere(['like', 'type', $this->type]);
return $dataProvider;
}
按字符串值搜索时,我得到一个空结果。按整数值搜索生成数据
感谢您的帮助。谢谢 也许您最好对该列进行筛选,而不是按字符串搜索。您可以按如下方式对字符串执行此操作
$filter = [
'example1' => 1,
'example2' => 2,
'example3' => 3,
];
$query->andFilterWhere(['like', 'type', $this->filter[$this->type]);
还是在这个地方
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->filter[$this->type],
])
您还可以在列上创建过滤器下拉列表,对于该过滤器的下拉列表,您可以传递该数组并执行以下操作
$query->andFilterWhere([
'type' => $this->type,
])
也许你最好对该列进行筛选,而不是按字符串搜索。您可以按如下方式对字符串执行此操作
$filter = [
'example1' => 1,
'example2' => 2,
'example3' => 3,
];
$query->andFilterWhere(['like', 'type', $this->filter[$this->type]);
还是在这个地方
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->filter[$this->type],
])
您还可以在列上创建过滤器下拉列表,对于该过滤器的下拉列表,您可以传递该数组并执行以下操作
$query->andFilterWhere([
'type' => $this->type,
])
为什么要在查询对象中创建映射机制?好的,您可以在应用程序的前端将整数类型显示为字符串,但查询不应该包含表示的详细信息。您应该在搜索模型中将字符串类型映射为整数类型。例如:
class ReportSearchModel extends ReportModel
{
public function mapType($value)
{
$items = [
'addacs' => 0,
'arudd' => 1
];
return array_key_exists($value, $items) ? $items[$value] : null;
}
public function search($params)
{
//another code
$query->andFilterWhere([
'type' => $this->mapType($this->type),
])
//another code
}
}
另一种方法是使用,而不是映射 为什么要在查询对象中创建映射机制?好的,您可以在应用程序的前端将整数类型显示为字符串,但查询不应该包含表示的详细信息。您应该在搜索模型中将字符串类型映射为整数类型。例如:
class ReportSearchModel extends ReportModel
{
public function mapType($value)
{
$items = [
'addacs' => 0,
'arudd' => 1
];
return array_key_exists($value, $items) ? $items[$value] : null;
}
public function search($params)
{
//another code
$query->andFilterWhere([
'type' => $this->mapType($this->type),
])
//another code
}
}
另一种方法是使用,而不是映射