/**
* Creates an [[ActiveQuery]] instance.
* This method is called by [[find()]], [[findBySql()]] to start a SELECT query.
* You may override this method to return a customized query (e.g. `CustomerQuery` specified
* written for querying `Customer` purpose.)
* @return ActiveQuery the newly created [[ActiveQuery]] instance.
*/
public static function createQuery()
{
return new ActiveQuery(['modelClass' => get_called_class()]);
}
public static function createQuery()
{
return new MyActiveQuery(['modelClass' => get_called_class()]);
}
then in MyActiveQuery
public function init()
{
parent::init();
$condition = "AND .... .... ..";
$this->where($condition);
}
It works until you call MyActiveRecord::find(1) 'cos it always overwrites $this->where
EDIT:
in this way It works both with MyActiveRecord::find(1) and ActiveRecord (it uses query->all() and without filters it doesn’t call where() function) but I have to overwrite 2 methods
public function init()
{
parent::init();
$this->andWhere($this->myDefaultCondition());
}
public function where($condition, $params = [])
{
parent::where($condition, $params);
return $this->andWhere($this->myDefaultCondition());
}
Not only that, but the ActiveRecord::find() function actually calls the createQuery() function. So it shouldn’t be substituting it, but instead adding to it.
public static function find($q = null)
{
$query = static::createQuery();
if (is_array($q)) {
return $query->where($q)->one();
} elseif ($q !== null) {
// query by primary key
$primaryKey = static::primaryKey();
if (isset($primaryKey[0])) {
return $query->where([$primaryKey[0] => $q])->one();
} else {
throw new InvalidConfigException(get_called_class() . ' must have a primary key.');
}
}
return $query;
}
Ok, I see now - the problem is specifically with the find() function. In that case, you should be able to just override the find() itself (in addition to the createQuery()).
Yes in Yii2 is dropped, because this method make many problems.
You can simple add default scope, e.q
class Post extends ActiveRecord
{
public static function find($q = null)
{
return parent::find()->defaultOrder();
}
public static function defaultOrder($query)
{
$query->order('id desc');
}
}
It works perfect and is more flexibel than the old default scpope