tighten / parental

Use single table inheritance in your Laravel app
MIT License
1.36k stars 98 forks source link

Allows a Children to be extended #115

Open RomainMazB opened 1 year ago

RomainMazB commented 1 year ago

Hi!

Working in a game environment, I have a Building model instance using STI to store buildings like "tree", "oasis", "house" and so on.

class Building extends Model
{
    use \Parental\HasChildren;
}

class Tree extends Building
{
    use \Parental\HasParent;
}

class Oasis extends Building
{
    use \Parental\HasParent;
}

I wanted to extend the Oasis class into a GreatOasis one with some difference into the class constants to slightly improve the building's performance.

class GreatOasis extends Oasis
{
    public const MINIMUM_VITALITY = 40;
}

The issue is that when the package looks for the parent class from the GreatOasis class, it fails because its direct parent is Oasis and not the Building model class, so the table name results in oases instead of buildings:

Next Illuminate\Database\QueryException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "oases" does not exist LINE 1: update "oases" set "vitality" = $1, "updated_at" = $2 where ... ^ (Connection: pgsql, SQL: update "oases" set "vitality" = 70, "updated_at" = 2023-08-24 15:08:43 where "id" = 2732) in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:793

With this PR, it allows a Children to be extended as many as wanted, the parent will be defined by the first parent class using the HasParent trait, or defaults to its direct parent.