saritasa/eloquent-custom

该包已被 放弃 并不再维护。未建议替代包。

Saritasa 对 Eloquent 的定制

1.2.0 2022-07-18 15:20 UTC

This package is auto-updated.

Last update: 2024-09-18 20:09:50 UTC


README

PHP CodeSniffer Release PHPv Downloads

Eloquent 的自定义扩展

查看 https://laravel.net.cn/docs/eloquent

Laravel 5.x/6.x

安装 saritasa/eloquent-custom

$ composer require saritasa/eloquent-custom

可选 (如果您想使用默认迁移): 如果您使用 Laravel 5.4 或更低版本,或者 5.5+ 且禁用了 包发现,请在 config/app.php 中添加 PredefinedMigrationsServiceProvider 服务提供者

'providers' => array(
    // ...
    Saritasa\Database\Eloquent\PredefinedMigrationsServiceProvider::class,
)

然后您可以执行以下命令

php artisan vendor:publish --provider=Saritasa\Database\Eloquent\PredefinedMigrationsServiceProvider --tag=migrations

可用类

实体

扩展 Eloquent 模型,添加

  • 为新创建的继承者设置默认字段值的abilities

示例:

class User extends Entity
{
    protected $defaults = [
        'role' => 'user'
    ]
}

现在如果您创建新用户,它将默认具有 'user' 角色,如果您没有显式提供它

$user = new User(['name' => 'John Doe']);
$this->assertEquals('user', $user->role); // true

$admin = new User['name' => 'Mary', 'role' => 'admin');
$this->assertEquals('admin', $admin->role); // true

SortByName

全局范围 Eloquent 模型,默认按名称排序

示例:

class SomeModel extends Model {
...
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new \Saritasa\Database\Eloquent\Scopes\SortByName());
    }
...
}

CamelCaseModel

扩展类 Model,用于在数据库中使用驼峰命名法。

示例:

use Saritasa\Database\Eloquent\Models\CamelCaseModel;

class SomeModel extends CamelCaseModel
{
    //your code
}

CamelCaseForeignKeys 特性

在任何模型类中使用,以获取此模型的默认外键名称。默认情况下,Eloquent 使用蛇形命名法的外键,此特性将名称转换为驼峰命名法,如 carModelId 而不是 car_model_id。如果您的现有外键已经是驼峰命名法,请使用它。

示例:

use Saritasa\Database\Eloquent\Models\CamelCaseForeignKeys;

class MyModel extends SomeModelClass
{
    use CamelCaseForeignKeys;
}

贡献

如果您想做出贡献(拉取请求)或只是在您自己的环境中构建和测试项目,请查看 CONTRIBUTING行为准则

资源