yiisoft / yiisoft/active-record

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

Open
#60 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
119
Forks
38
Avg merge
1h 11m
Merged PRs (30d)
1

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the getPictures() relation using viaTable('dbl_album_picture', ...) and the $album->getPictures()->count() call shown in the issue. Compare the generated SELECT statements with the expected single count query; done means the count operation no longer performs the extra relation lookup and produces the expected result.

Written by the indexing model from the issue text.

Assessment

Tech stack
php, sql
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.