1

I'm not sure of the right terminology here but I think this is quite easy to do in Yii2 but I can't seem to find how.

I want to have a class Location which extends ActiveRecord but I have two types of locations. To handle this I will have a field called location.type which is enum ('store','campus'). Then I want to create two models that extend Location named Store and Campus with each only returning results based on the type field.

I saw that I think Yii1.x allowed a model method named find() that might work like this:

public model find()
{
    return $this->andWhere(['type' => 'store']);
}

But this doesn't work in Yii2. Is what I'm doing sound like the correct approach? How can I best achieve this?

Edit: I've found that I should be using ActiveQuery as described here*. However the method active() (or whatever method I name it) is not called. I seem to be missing something.

*http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#customizing-query-classes

Dubby
  • 2,290
  • 4
  • 27
  • 38

1 Answers1

1

OK, what I needed to do was a lot simpler. I just needed to override the model's find() method like so:

public static function find()
{
    return parent::find()->where(['type' => store']);
}
Dubby
  • 2,290
  • 4
  • 27
  • 38
  • yes that is the simplest way but if you need a better approach to handle more complex cases then I would recommand this: http://stackoverflow.com/questions/31948917/yii2-activequery-example-and-what-is-the-reason-to-generate-activequery-class/31950149#31950149 – Salem Ouerdani Apr 01 '16 at 20:19