Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search between two dates in yii2

Tags:

php

yii2

A date can be represented in different formats. A table itself looks like so:

   book varchar(250) NOT NULL,  
   date INT NOT NULL

Now my problem is that I can not implement search in range between two dates. For example, there are 5 books with different dates, but the start date starts at 31/12/14 and final date is 31/02/15. So when a user selects a range between these dates, it must provide all books in that date range.

Is there any way to do it in Yii2? I could not find anything so far

UPDATE

I'm implementing a custom filter which doesn't belong to GridView and it looks like as a standalone box outside the table.

It looks like so:

<div class="custom-filter">

   Date range:
     <input name="start" />
     <input name="end" />

   Book name:
     <input name="book" />

</div>
like image 657
Yang Avatar asked May 19 '15 12:05

Yang


2 Answers

I believe this is the answer you need:

$model = ModelName::find()
->where(['between', 'date', "2014-12-31", "2015-02-31" ])->all();
like image 91
Leye Odumuyiwa Avatar answered Nov 15 '22 21:11

Leye Odumuyiwa


If you get start and end in date format, but date in your database table is in INT type, you must do something like this:

//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();

Not forget validate values given from post.

like image 24
pa3py6aka Avatar answered Nov 15 '22 21:11

pa3py6aka