问题描述
$query->andFilterWhere(['like','date_of_birth',date('d-m-Y',strtotime($this->date_of_birth))]);
它不起作用..
解决方法
¿你在使用 MySQL 吗?那么日期格式为:YYYY-MM-DD。这就是 MySQL 的工作方式,您无法更改。
您可以在您的网站和表单上以您想要的格式显示日期,但是您必须将它传递给 MYSQL,因为 MYSQL 期望接收它。所以你应该做的是:
在您的模型类中:
<?php
$model->date_of_birth = !empty($model->date_of_birth) ? Yii::$app->formatter->asDate($model->date_of_birth,'php:d-m-Y') : null;
?>
查看文档了解更多信息:
https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#beforeSave()-detail
为了在您的表单和视图中再次显示此日期:
$query->andFilterWhere(['date_of_birth' => $this->date_of_birth]);
更新:
要使过滤器在(例如)格式化日期时在 gridview 中工作,您应该修改 YourModelSearch.php 模型类中的比较:
从这里:
/* Change the format to MySQL Date Format when compares */
$query->andFilterWhere(['date_of_birth' => Yii::$app->formatter->asDate($this->date_of_birth,'php:Y-m-d')]);
为此:
'components' => [
...
'formatter' => [
'class' => 'yii\i18n\Formatter','timeZone' => 'Europe/London','defaultTimeZone' => 'Europe/London','dateFormat' => 'd/M/Y','datetimeFormat' => 'd/M/Y H:m','timeFormat' => 'H:m:s','decimalSeparator' => ',','thousandSeparator' => '','currencyCode' => 'EUR','locale'=>'es_ES'
],...
]
在你的 config/web.php 中你应该有这样的东西:
{{1}}
永远不要将 LIKE 比较器与 Date 类型一起使用。