-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AR Default scope generates WHERE condition in relations. #3565
Comments
This is how it is designed to work. Yii doesn't know when it should magically put WHERE to ON, and it shouldn't do so. |
you can use |
Yes but in this case I do the following public function getDocuments()
{
$query = $this->hasMany(Document::className(), ['user_id' => 'id']);
$query->onCondition($query->where);
$query->where = null;
return $query;
} Doesn't looks great to me |
I mean in find() you can use onCondition() instead of where() |
correct, but I still need to remove WHERE condition from result sql |
what code generated you that query? looks wrong to me as document.deleted should be in ON when specified via onCondition. |
Ok say I have 2 models User and Document. User has default scope class User extends ActiveRecord
{
/**
* @return \yii\db\ActiveQuery
*/
public static function find()
{
return parent::find()->where('user.deleted = 0');
}
}
class Document extends ActiveRecord
{
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
// yes I can add onCondition here but where will be left
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
// then look into hasOne hasMany
public function hasOne($class, $link)
{
$query = $class::find(); // this will call User::find() and here we get query with default where
$query->primaryModel = $this;
$query->link = $link;
$query->multiple = false;
return $query;
} |
The solution would be to overwrite public static function find()
{
return parent::find()->onCondition('user.deleted = 0');
} this will add 'user.deleted = 0' to ON when joining the relation and to WHERE when just finding users. We should add this to the docs. |
Thanks! |
@cebe any suggestion about where to document it? |
this is more like a cookbook things than something for the guide... |
Added as an issue to cookbook repo. Closing this one as we're not going to add it to the guide. |
Right now we have
therefore when we join model with default scope we have default condition in WHERE instead of ON condition. If we use LEFT join query doesn't work as expected.
SQL example
LEFT JOIN doesn't work in this case cause
The text was updated successfully, but these errors were encountered: