N
N
nepster-web2014-05-28 16:36:19
Yii
nepster-web, 2014-05-28 16:36:19

Yii2 - how to make a selection of records?

There is a method that should count the number of comments:

public function getCountComments() {

        $condition = [];
        
        if($this->post_id) {
            $condition['post_id'] = $this->post_id;
        }
        
        if($this->type) {
            $condition['type'] = $this->type;
        }
        
        return self::find()
                    ->where($condition)
                    ->count();
    }

Everything works great. Now I need to slightly expand this method as follows. I want to add a period flag and based on it display the number of comments per day for example.
That is, something like this:
public function getCountComments($period = false) {

        $condition = [];
        
        if($this->post_id) {
            $condition['post_id'] = $this->post_id;
        }
        
        if($this->type) {
            $condition['type'] = $this->type;
        }
        
        // Выборка за определенный период 
        if($period == 'day') {
            return self::find()->where('date_create>=CURDATE()')->count();
        }
        
        return self::find()
                    ->where($condition)
                    ->count();
    }

But the problem is that I can't write where correctly.
That is, if $period == 'day' then you need to make a selection considering post_id, type and CURDATE().
I tried to sculpt addWhere or addCondition there but it did not work out. Please tell me how to make such a request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Zelenin, 2014-05-29
@nepster-web

public function getCountComments($period = false) {

        $query = self::find();

        if($this->post_id) {
            $query->where(['post_id' => $this->post_id]);
        }

        if($this->type) {
            $query->andWhere(['type' => $this->type]);
        }

        if($period == 'day') {
            $query->andWhere('date_create>=CURDATE()');
        }

        return $query->count();
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question