Question

I have a laravel 4 application and in this application I need to define a model with relation to another model 2 times but with discrimination on type.

Example

class Car extends Eloquent{

     public function oldDrivers(){
        return $this->hasMany('Driver');
     }

     public function newDrivers(){
        return $this->hasMany('Driver');
     }

}

so the relation will be the car Id at the driver's table, the thing is when I want to get the old drivers only for a certain car, it returns all drivers from both relations.

When looking into it I found because it is the same table, so now I set a type in the Driver model, now I want my relation to be filtered by this type, so the oldDrivers will be only drivers with the type of oldDrivers and new drivers will be the Drivers with only the newDriver type set,

How can this be done in Laravel ?

Was it helpful?

Solution

You may try something like this:

class Car extends Eloquent{

     public function oldDrivers(){
        return $this->hasMany('Driver')->where('type', 'olddrivers');
     }

     public function newDrivers(){
        return $this->hasMany('Driver')->where('type', 'newdrivers');
     }

 }

Assumed that you have type field as a filter in your database. If I'm wrong about type field then you just change the field name to the right one because you got the idea that how can you add filter using a where clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top