Can anyone point me in the right direction to implement the defaultScope similair to how it worked in Yii1?
I tried adding it to my ActiveQuery extension (thru init), and apply andWhere to it, but this does obviously not work in case of LEFT JOIN's (it will add the conidtion to the where, making the LEFT an INNER JOIN).
I don't know where to implement it otherwise neither how to check if current query is part of a JOIN or primary table (then I could switch the condition to on instead of where).
Thanks in advance.
class ActiveQuery extends \yii\db\ActiveQuery {
public function init()
{
$this->applyDefaultScope();
parent::init();
}
/**
* @param ActiveQuery $query
* @return ActiveQuery
*/
public function applyDefaultScope(){
$modelClass = $this->modelClass;
/** @var TableSchema $modelSchema */
$modelSchema = $modelClass::getTableSchema();
foreach ($modelSchema->columns as $name => $column) {
if ($name === 'active') {
$this->andWhere([$modelSchema->name.'.'.$name => 1]);
}
if (substr($name, -7) === '_active') {
$this->andWhere([$name => 1]);
}
}
}
}
_This is an automated comment, triggered by adding the label question._
Please note, that the GitHub Issue Tracker is for bug reports and feature requests only.
We are happy to help you on the support forum, on IRC (#yii on freenode), or Gitter.
Please use one of the above mentioned resources to discuss the problem.
If the result of the discussion turns out that there really is a bug in the framework, feel free to
come back and provide information on how to reproduce the issue. This issue will be closed for now.
Seriously? This is the first place for people to ask these questions, I'd say archiving it here is wise ;-) But ok, I'll move over.
This is the replacement of scopes in yii2: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#customizing-query-classes
@cebe We have hundreds of models, I'd prefer not to create a query class for all of them - if not needed.
But I'll built in the same approach at some generic point in my code. Thanks, helpfull.
@RdeWilde, if you have many different models which share specific query configuration, you can choose to extend from your own ActiveRecord (extending from \yii\db\ActiveRecord). You can also use traits for overriding find() if you dont want to rely on inheritance too much. Finally, you can work with events to reach your goal. An old topic on this matter is https://github.com/yiisoft/yii2/issues/4048