日期可以用不同的格式表示.表本身看起来像这样:
book varchar(250) NOT NULL,
date INT NOT NULL
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我无法在两个日期之间的范围内实现搜索.例如,有5本书具有不同的日期,但开始日期开始于31/12/14,最终日期为31/02/15.因此,当用户选择这些日期之间的范围时,它必须提供该日期范围内的所有书籍.
有没有办法在Yii2中做到这一点?到目前为止我找不到任何东西
UPDATE
我正在实现一个不属于的自定义过滤器,GridView它看起来像一个独立的盒子在桌子外面.
它看起来像这样:
<div class="custom-filter">
Date range:
<input name="start" />
<input name="end" />
Book name:
<input name="book" />
</div>
Run Code Online (Sandbox Code Playgroud)
小智 25
我相信这是你需要的答案:
$model = ModelName::find()
->where(['between', 'date', "2014-12-31", "2015-02-31" ])->all();
Run Code Online (Sandbox Code Playgroud)
pa3*_*aka 11
如果您以日期格式获取开始和结束日期,但数据库表中的日期是 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();
Run Code Online (Sandbox Code Playgroud)
不要忘记验证帖子给出的值。
小智 5
假设存储为整数的日期代表 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;
}
}
Run Code Online (Sandbox Code Playgroud)
查看更多有关timestampAttribute在本文档。
使用Yii2 Active Record并在两个日期之间访问书籍,如下所示。
public static function getBookBetweenDates($lower, $upper)
{
return Book::find()
->where(['and', "date>=$lower", "date<=$upper"])
->all();
}
Run Code Online (Sandbox Code Playgroud)
我假设您正在使用活动记录类,并且您已经创建了 Book.php (基于表名的适当名称)作为模型文件。