Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Can I pre-filter models?

Let's suppose I have a table that represents a vehicle, called Vehicles, and a Phalcon\Model\Vehicles class. There is a type field that represents the type of the vehicle, let's say: car, truck, boat. In my application, I want to provide custom methods for the model class depending on the type of the vehicle. So I did:

class Vehicles extends \Phalcon\Mvc\Model { ... }

class Cars extends Vehicles { 
    protected $type = 'car';
class Boats extends Vehicles { 
    protected $type = 'boat';

It works fine if I want to create that type of object:

$boat = new Boats();

Now, let's say I have Users that own vehicles, and I do something like this:

class Users extends \Phalcon\Mvc\Model { 

    public function initialize()
        $this->hasMany('id', 'Vehicles\Boats', 'users_id', array('alias' => 'Boats'));
        $this->hasMany('id', 'Vehicles\Cars', 'users_id', array('alias' => 'Cars'));

If I call $user->getBoats(), the Phalcon\Model's magic method will call getRelationRecords of the modelsManager and return all records from the table vehicles.

Now my question is: is there a way to pre-filter this so I only get one type of record? I guess I'd need to implement a getBoats method and do all the logic there. What do you think?

Is there a better way to accomplish this?


I think this is what you are searching for


Sweet, thanks!