How Single Table Inheritance works with Parental
mainParental allows you to extend a model to add specific behavior while referencing the same database table.
- Use the
HasChildrentrait on the parent model to allow it to act as a base for multiple child types and to enable automatic instantiation of child models when querying the parent. - Use the
HasParenttrait on child models to tell Eloquent to use the parent's table instead of looking for a table named after the child class.
This solves the problem where Laravel normally expects a separate table for every model class.
// The "parent"
class User extends Model
{
use HasChildren;
}
// The "child"
class Admin extends User
{
use HasParent;
public function impersonate($user) {
//...
}
}
// Returns "Admin" model, but references "users" table:
$admin = Admin::first();
$admin->impersonate($user);