jeudi 3 mars 2016

PHP Laravel Eloquent: has many-relation with child classes

Let's say I have the Relations...

abstract class Furniture extends Model{...]
class Chair extends Furniture{...}
class Table extends Furniture(...)

... also there is the room class...

class Room extends Model{...}

The following eloquent relations are given...

class Room extends Model{
    public function furnitures(){
        return $this->hasMany("App/Furniture");
    }
}

abstract class Furniture extends Model{
    public function room(){
        return $this->belongsTo("App/Room");
    }
}

Our goal is, that calling...

$room->furnitures;

... returns an array of different, inherited furniture objects. So if I do something like this:

foreach($this->furnitures as $fur){
    echo get_class($fur)." -> ".get_parent_class($fur)."\n";
}

Would result in something like:

Chair -> Furniture
Table -> Furniture
Table -> Furniture
Chair -> Furniture
Chair -> Furniture

Right now, that is not possible, because of the abstract class, which is instantiated by default.

Is it possible to create such a relation in eloquent? If yes how to realize it?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TaqWug
via IFTTT

Aucun commentaire:

Enregistrer un commentaire