R
R
Roman Savitsky2018-05-15 22:34:33
MySQL
Roman Savitsky, 2018-05-15 22:34:33

How to get the number of comments (in 3 identical separate tables) of each post using hasMany?

Good evening everyone!
In general, how to get the number of comments for each entry, if the Comments are in the same table, then in the post model we write the final as well:

public function getComment()
    {
        return $this->hasMany(Comments::className(),['post_id' => 'id'])->select('id,post_id');
    }

But the problem is slightly different, I have 3 identical tables with comments:
1) Таблица - comments_blog
2) Таблица - comments_blog_2
3) Таблица - comments_blog_3

Comments will be distributed among the table depending on the remainder of the division of ID - entries by 3 (ie $id % 3);
Now here is the dilemma, how to connect 3 Comment models into one, how to connect all this through UNION and put it in $this->hasMany() or in another way I don’t understand. I will be glad for any help.
Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Savitsky, 2018-05-16
@PRC

In general, everything turned out to be easier than I thought) Here, if anyone is interested.
Since I already had a method that returned the full path to the Class of each individual comment table, then in the Post Class we write this:

public function getComment($postID)
    {
        return $this->hasMany(ComentsBlogObject::changeDB($postID)::className(),['post_id' => 'id'])->select('COUNT(*)');
    }

Well, in the controller, we check that we got everything right:
$model = ArticleBlog::find()->limit(3)->all();
foreach ($model as $key => $value) {
            print_r($value->getComment($value->id)->count() );
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question