user1236524
user1236524

Reputation:

Yii2: How to filter by 'date' and by 'time' from a 'datetime' db column

In a user table I have a created_at column. In a User AR model that becomes a property, and in \yii\grid\GridView I split that property onto 'columns' => ['created_at:date', 'created_at:time'],

Question: How do I habilitate a search field for those respective given columns, I mean they aren't actual db columns, therefore not model properties. so I can't do

$query->andFilterWhere([
            'crated_at_date' => $this->crated_at_date,
            'created_at_time' => $this->created_at_time,
        ]);

I know the search field is related to \yii\grid\Column::filterOptions but more specifically I don't know how to specify the andFilterWhere() clause within the search model.

Upvotes: 1

Views: 6353

Answers (2)

Ziya Vakhobov
Ziya Vakhobov

Reputation: 465

You can filter more or less just by converting input datatime to time:

$query->andFilterWhere([
    '>=', 
    'crated_at_date_time', 
    strtotime($this->crated_at_date)
])

Upvotes: 0

Insane Skull
Insane Skull

Reputation: 9358

In searchModel() you can try this way:

$query->andFilterWhere([
    'like', 
    'FROM_UNIXTIME(created_at, "%Y-%m-%d")', 
    $this->crated_at_date
])
->andFilterWhere([
    'like', 
    'FROM_UNIXTIME(created_at, "%h:%i:%s %p")', 
    $this->created_at_time
])

Well, It's not tested but I guess it will do the trick.

FROM_UNIXTIME()

Upvotes: 2

Related Questions