Yii2: Returns an empty relations for models with composite primary key

Created on 9 Oct 2019  路  3Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

create model Article and Tag:

class Article extends ActiveRecord
{
//...
    public static function primaryKey()
    {
        return ['id', 'lang'];
    }

    /**
    * @return \yii\db\ActiveQuery
    */
    public function getTags()
    {
        return $this->hasMany(Tag::class, ['id' => 'rel_id'])
            ->viaTable('article_has_tag', ['owner_id' => 'id', 'owner_lang' => 'lang']);
    }
    //...
}

Article table:

| id | lang | title |
| --- | --- | --- |
| 1 | ru | article1 |

ArticleHasTag table:

| owner_id | owner_lang | rel_id |
| --- | --- | --- |
| 1 | ru | 1 |
| 1 | ru | 2 |

Tag table:

| id | title |
| --- | --- |
| 1 | tag1 |
| 2 | tag2 |

Then i try find one article with tag where tags.id=1 and get all related to this article tags:

$result = Article::find()
    ->joinWith(['tags'])
    ->where(['tags.id' => 1])
    ->one()
    ->toArray([],['tags']);
print_r($result);

What is the expected result?

Array
(
    [id] => 1
    [lang] => ru
    [tags] => Array
        (
             [id] => 1,
             [title] => tag1
        ),
        (
             [id] => 2,
             [title] => tag2
        )
)

What do you get instead?

Array
(
    [id] => 1
    [lang] => ru
    [tags] => Array
        (
        )
)

Solution

This issue dublicate https://github.com/yiisoft/yii2/issues/5004, but with more info how reproduce problem
Solution in the commit https://github.com/yiisoft/yii2/pull/9371/commits/3799bf19b673e73902c66c6f71a7ef8ccee6bdd8

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.?
| PHP version |
| Operating system |

db bug

Most helpful comment

Sure, i will help close this issue with new pull request.

All 3 comments

9371

The code in the commit referenced is based on very old files and cannot be applied to current version of Yii as is. @dizairo do you have time to put together a new pull request?

Sure, i will help close this issue with new pull request.

Was this page helpful?
0 / 5 - 0 ratings