I am getting data from 3 tables thanks to yii2 eager loading. But also, I need to run one COUNT() function to count number of returned rows from one table. If I run it inside select() method, my query will fail saying "Trying to get property of non-object" if I try to display result from one of the joined tables.
I want to count number of post_id in my comment table, executed by this query. ( I want to get comments along with posts that they belong too and users that made those comments, plus count number of posts ( defined by $posts array ) that have comments.
You wrote "AS count". You could try to write "AS counting", because "count" is a reserved SQL keyword. Then you have to create the "counting" attribute in the class Comment:
If I do it like that now I get another error : Trying to get property of a non object, most likely because my query hasn’t selected necessary fields from related tables, and I do not know how to disambiguate them.
foreach ($comments as $data) {
echo $data->post->title; // error - unknown column in the field list
}
If I try to select like this I will get sql error because I do not know how to disabiguate fields that have the same name in all 3 tables ( for example id, or title )
->select(['post.id', 'post.title', 'COUNT(user_id) AS userCount'])