日期可以用不同的格式表示。表本身如下所示:
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>
我相信这是你需要的答案:
$model = ModelName::find()
->where(['between', 'date', "2014-12-31", "2015-02-31" ])->all();
如果以
日期格式获取开始和结束,但数据库表中的日期为 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();
不要忘记验证帖子给出的值。
假设存储为整数的日期表示 unix 时间戳,您可以创建一个模型类并对start
和end
属性应用 yii''validators''DateValidator。
/**
* 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
的更多信息,请参阅本文档。
使用 Yii2 活动记录并在两个日期之间访问书籍,就像这样。
public static function getBookBetweenDates($lower, $upper)
{
return Book::find()
->where(['and', "date>=$lower", "date<=$upper"])
->all();
}
我假设您正在使用活动记录类,并且您已经创建了 Book.php(基于表名的适当名称(作为模型文件。