active-record icon indicating copy to clipboard operation
active-record copied to clipboard

count() for relation with viaTable buid two queries with IN (....)

Open lobzenko opened this issue 8 years ago • 3 comments

image

What steps will reproduce the problem?

Trying to get count of records for relation with viaTable

public function getPictures()
{
        return $this->hasMany(Picture::className(), ['id_picture' => 'id_picture'])
                    ->viaTable('dbl_album_picture', ['id_album' => 'id_album']);
}

like that

$album->getPictures()->count();

What is the expected result?

SELECT count(*) FROM dbl_album_picture WHERE id_album=1

What do you get instead?

SELECT * FROM dbl_album_picture WHERE id_album=1 SELECT COUNT(*) FROM db_picture WHERE id_picture IN ('13', '14', '16', '17', '18', '19', '20')

Additional info

Q A
Yii version 2.0.12
PHP version PHP 7.0.8

lobzenko avatar Oct 25 '17 09:10 lobzenko

You're counting pictures, not records from dbl_album_picture so I suppose SQL generated is correct.

samdark avatar Oct 25 '17 09:10 samdark

count from dbl_album_picture its count of related Models. isnt it? If i have 100-1000 link records in dbl_album_picture its generate IN (1000 id's)? And take the memory for build this.

I can use plain SQL for counting, but count() with relation would be more convenient. How i can get only count from relation with viaTable?

lobzenko avatar Oct 26 '17 08:10 lobzenko

While the result is correct, this can be optimised to not fetch all related records for the count.

cebe avatar Oct 26 '17 08:10 cebe