D
D
Daniil Sidorov2021-02-17 20:54:35
Yii
Daniil Sidorov, 2021-02-17 20:54:35

How to correctly compose an ActiveQuery query in Yii2?

Good afternoon. I am engaged in the internationalization of the site on Yii2. I'm trying to make a request to get an entity with a translation. I have the following table structure:
602d5185d2197761239193.png
In the Sale model, I registered the relationship:

public function getTranslate()
{
    return $this->hasMany(SaleI18n::className(), ['sale_id' => 'id']);
}

I wrote the following in SaleQuery : I
made the second condition so that if there is no translation for this record, then nothing would be returned.
public function withTranslate($lang = null)
{
    if (!$lang)
    {
        $lang = Yii::$app->language;
    }

    return $this->joinWith('translate')
        ->andOnCondition([
            'and',
            [
                'SaleI18n.lang' => $lang
            ],
            [
                '!=', 'SaleI18n.id', null
            ]
        ]);
}

After which I tried to get some entry:
Sale::find()->withTranslate('en')->where(['alias' => 'becomePartner', 'active' => 1]);

In response, I get an empty result. This generates the following SQL query:
SELECT `Sale`.* FROM `Sale` LEFT JOIN `SaleI18n` ON `Sale`.`id` = `SaleI18n`.`sale_id` WHERE ((`alias`='becomePartner') AND (`active`=1)) AND ((`SaleI18n`.`lang`='en') AND (`SaleI18n`.`id` != NULL))

I noticed that if I execute the query directly in the database, removing it AND (`SaleI18n`.`id` != NULL)and changing it to just , then I get the record I need with the translation . Removing the second condition in withTranslate() has no effect. Replacing andOnCondition with andWhere generally removes the conditions I specified from the request. It seems to me that I am confused in the simplest things. Please tell me how to make a function to get the translation from the linked table so that if there is no translation, the entire query would return nothing. And how then to operate with this data? Thank you! SELECT `Sale`.*SELECT *



Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
toratoda, 2021-02-18
@toratoda

Sale::find()->withTranslate('en')->where(['alias' => 'becomePartner', 'active' => 1]);

you didn't forget at the end ->one()either ->all()?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question