Answer the question
In order to leave comments, you need to log in
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:
In the Sale model, I registered the relationship:
public function getTranslate()
{
return $this->hasMany(SaleI18n::className(), ['sale_id' => 'id']);
}
public function withTranslate($lang = null)
{
if (!$lang)
{
$lang = Yii::$app->language;
}
return $this->joinWith('translate')
->andOnCondition([
'and',
[
'SaleI18n.lang' => $lang
],
[
'!=', 'SaleI18n.id', null
]
]);
}
Sale::find()->withTranslate('en')->where(['alias' => 'becomePartner', 'active' => 1]);
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))
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question