Here are my (simplified) models:
abstract class Animal extends Illuminate\Database\Eloquent\Model
{
protected $name;
}
class Cat extends Animal
{
}
class Dog extends Animal
{
}
Cats and dogs have several other attributes. I've made animal abstract as each animal will be a cat or a dog, so there will be no actual instances of animal.
Now, I want to be able to list:
Cat::all() should retrieve all cats.Dog::all() should retrieve all cats.Animal::all() should retrieve all cats and dogs.Is this generally possible with eloquent? If, yes: Should I use Polymorphic Relations for that purpose?
There's no support for that in Eloquent.
If Cat and Dog have similar properties, a single animals table is probably the best solution. You can use scopes to only get one species:
class Animal extends Illuminate\Database\Eloquent\Model
{
public function scopeCats($query)
{
return $query->where('species', 'cat');
}
}
$cats = Animal::cats()->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With