Search code examples
phpyii2

How to add between in query builder?


I am implementing a custom search, and now I need to select values in range for date column.

public function search($params)
{
    $query = Books::find();
    //.....
    
    $timestampStart = strtotime($this->dateStart),
    $timestampEnd = strtotime($this->dateEnd)
    
    // How to add BETWEEN here?!!?!
    $query->andBetween('date', $timestampStart, $timestampEnd) // pseudo-code

From the documentation, it's not entirely clear how to use that: https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md


Solution

  • From the docs here, you can use a where method call for this.

    between: operand 1 should be the column name, and operand 2 and 3 should be the starting and ending values of the range that the column is in. For example, ['between', 'id', 1, 10] will generate id BETWEEN 1 AND 10.

    So, in your case, it would look something like:

    $query->where(['between', 'date', $timestampStart, $timestampEnd]);
    

    For more information on building queries, you can also see this.