proai/eloquent-inheritance

受 Rails 实现启发的 Laravel 单表继承

v0.1.5 2024-08-26 19:26 UTC

This package is not auto-updated.

Last update: 2024-09-23 19:53:13 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

单表继承是一种在关系型数据库中模拟面向对象继承的方法。虽然像 Ruby on Rails 这样的其他框架有内置的实现,但 Laravel 没有提供。此包旨在为 Laravel 提供尽可能简单的实现。

安装

您可以通过 composer 安装此包

composer require proai/eloquent-inheritance

请注意,您需要至少 PHP 8.0Laravel 9 才能使用此包。

使用

首先,您需要将 Inheritance 特性添加到您的根模型中

use ProAI\Inheritance\Inheritance;

class Pet extends Model
{
    use Inheritance;

    //
}

然后,您可以扩展其他使用相同表的模型来扩展根模型

class Cat extends Pet
{
    //
}

class Dog extends Pet
{
    //
}

请注意,为了使上述示例工作,您需要一个名为 pets 的表和一个名为 type 的列。

每次实例化 CatDog 模型时,属性 type 将设置为类的类名(例如 App\Models\Cat)。

除此之外,没有魔法,CatDog 模型将表现得像普通 Eloquent 模型一样。您可以在这些模型上定义猫或狗特定的属性和关系。例如,仅针对狗设置的属性应该在表中设置为可空列,以便为狗设置但它为其他宠物设置为 null

根模型行为

您可以像查询任何其他模型一样查询根模型。然而,返回的模型将根据类型名称进行转换。例如,如果有数据库中的一只猫和一只狗,则 Pet::all(); 将返回一个 Dog 模型和一只 Cat 模型。

当您在 $attributes 中指定类型时,无法使用 new Pet($attributes);。请改用静态方法 Pet::new($attributes)。此方法基于给定类型返回一个新的模型。例如,如果 $attributes 中的类型是 App\Models\Cat,则它将返回一个 App\Models\Cat 的实例。如果没有指定类型,则返回 App\Models\Pet 的实例。

自定义类型名称

如果您想使用与类名不同的名称作为类型列,可以使用静态属性 $inheritanceMap

class Pet extends Model
{
    use Inheritance;

    protected static $inheritanceMap = [
        'cat' => Cat::class,
        'dog' => Dog::class,
    ];
}

自定义类型列

默认情况下,类型列的名称为 type。但是,您可以设置自定义类型列名称

use ProAI\Inheritance\Inheritance;

class Pet extends Model
{
    use Inheritance;

    protected static $inheritanceColumn = 'pet_type';
}

支持

错误和功能请求在 GitHub 上跟踪。

许可证

此包在 MIT 许可证 下发布。