Automatically filtering with model inheritance


Feb '15

Apr '15

3

850

1


Thien
33.8k
edited Feb '15
Feb '15

Hi all

I have just share tip :)

Problem

Lets say that I have a table called data and a model called Data. Then I have Files that inherits from Data. Data is an abstract type and I want to store the actual type of the data in a single field.

I'm wondering how to by able to say Files::getFirstByVal($val) and have it supply the automatic SQL condition type = "file" when returning the rows. It would be fine in my case if I had to override some methods in the base class or in each class that inherits from Data.

Solution

When you use Phalcon\Mvc\Model::findFirst(), that's actually a shortcut to \Phalcon\Mvc\Model::find(). findFirst() just adds some extra conditions, then to calls find(). You can do the same thing with your custom getFirstByVal():

    public function getFirstByVal($val){
    $parameters = ['conditions'=>'key = :val: and type = "file','bind'=>['key'=>$val],'limit'=>1,'order'=>'key'];
    return parent::find($parameters);
  }

Done!!


Thien
14.2k

Hey man

What's up?

That doesn't really have anything to do with model inheritance. It's just the find params object.