[英]search between two dates in yii2
日期可以用不同的格式表示。 表本身看起來像這樣:
book varchar(250) NOT NULL,
date INT NOT NULL
現在我的問題是我無法在兩個日期之間的范圍內實現搜索。 例如,有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>
我相信這是你需要的答案:
$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 Active Record並在兩個日期之間訪問書籍。
public static function getBookBetweenDates($lower, $upper)
{
return Book::find()
->where(['and', "date>=$lower", "date<=$upper"])
->all();
}
我假設您正在使用活動記錄類,並且您已創建Book.php(基於表名稱的相應名稱)作為模型文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.