日期可以用不同的格式表示。表本身看起来是这样的:
book varchar(250) NOT NULL,
date INT NOT NULL现在我的问题是我不能在两个日期之间的范围内实现搜索。例如,有5本书有不同的日期,但是开始日期从31/12/14开始,最后的日期是31/02/15。因此,当用户在这些日期之间选择一个范围时,它必须提供该日期范围内的所有书籍。
在Yii2中有什么方法可以做到吗?到目前为止我什么都找不到
更新
我正在实现一个不属于GridView的自定义筛选器,它看起来像是表外的独立框。
看起来是这样的:
<div class="custom-filter">
Date range:
<input name="start" />
<input name="end" />
Book name:
<input name="book" />
</div>发布于 2016-06-21 10:08:06
我相信这就是你需要的答案:
$model = ModelName::find()
->where(['between', 'date', "2014-12-31", "2015-02-31" ])->all();发布于 2016-11-11 18:25:46
如果以日期格式获得开始和结束,但数据库表中的日期为INT类型,则必须执行如下操作:
//Get values and format them in unix timestamp
$start = Yii::$app->formatter->asTimestamp(Yii::$app->request->post('start'));
$end = Yii::$app->formatter->asTimestamp(Yii::$app->request->post('end'));
//Book name from your example form
$bookName = Yii::$app->request->post('book');
//Then you can find in base:
$books = Book::find()
->where(['between', 'date', $start, $end])
->andWhere(['like', 'book', $bookName])
->all();不要忘记验证来自post的值。
发布于 2019-01-06 11:58:03
假设以整数形式存储的日期表示unix时间戳,则可以创建一个模型类,并将yii\validators\DateValidator应用于start和end属性。
/**
* Class which holds all kind of searchs on Book model.
*/
class BookSearch extends Book
{
// Custom properties to hold data from input fields
public $start;
public $end;
/**
* @inheritdoc
*/
public function rules()
{
return [
['start', 'date', 'timestampAttribute' => 'start', 'format' => 'php:d/m/y'],
['end', 'date', 'timestampAttribute' => 'end', 'format' => 'php:d/m/y']
];
}
public function searchByDateRange($params)
{
$this->load($params);
// When validation pass, $start and $end attributes will have their values converted to unix timestamp.
if (!$this->validate()) {
return false;
}
$query = Book::find()->andFilterWhere(['between', 'date', $this->start, $this->end]);
return true;
}
}请参阅更多关于timestampAttribute on 这份文件的信息。
https://stackoverflow.com/questions/30325734
复制相似问题