A
A
alex4answ2019-04-22 18:42:00
Yii
alex4answ, 2019-04-22 18:42:00

How to make hasMany with condition in variable?

Good afternoon.
There are comments on the articles, I need to get the comments for the last 7, 28 days.
now I have done this:

Article model:
public function getComments7(){
        return $this->hasMany(Comments::className(), ['page_id' => 'id'])->andWhere('date > DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)');
    }
    
    public function getComments28(){
        return $this->hasMany(Comments::className(), ['page_id' => 'id'])->andWhere('date > DATE_SUB(CURRENT_DATE, INTERVAL 28 DAY)');
    }

and already in with() when selecting, I substitute what I need, but the problem is that you need to access comments differently
-> comments7 and -> comments28, which is not very convenient
. I tried to do it with JoinWith and already in the condition write for what period I comments are needed, but the result is generally empty.
What options are there besides LeftJoin to get pages and their latest comments ?
I don’t want to crutch and make it crooked, so I’m asking how best to proceed)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2019-04-22
@alex4answ

2 connections are not needed, one is enough

public function getComments($period=false){
        $query = $this->hasMany(Comments::className(), ['page_id' => 'id']);
        if($period){
             $query->andWhere('date > DATE_SUB(CURRENT_DATE, INTERVAL '.$period.' DAY)');
        }
        return $query;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question