naoray/eloquent-model-analyzer

提供一些有用的方法,以获取有关Eloquent模型类的更多信息。

资助包维护!
naoray

安装: 392,510

依赖项: 1

建议者: 0

安全: 0

星标: 16

关注者: 2

分支: 5

开放问题: 1

类型:

v4.0.0 2023-02-20 17:07 UTC

README

Software License Total Downloads Tests

分析Eloquent模型的关系和列可能会让人感到不知所措。这个小库旨在使其尽可能简单。

你可能想知道为什么你需要在运行时分析你的模型?!我能想到的所有场景都与分析代码库以生成一些代码片段有关。以下是一些可能用到的情况

安装

composer require naoray/eloquent-model-analyzer

使用方法

获取模型的所有关系

获取Eloquent模型的所有关系方法有三种不同的策略

  • 检查方法的返回类型
  • 从文档方法中提取返回类型
  • 直接调用方法并检查返回实例的类型
// User.php
class User extends Model
{
    public function parent()
    {
        return $this->belongsTo(self::class);
    }

    public function posts()
    {
        return $this->hasMany(Post::class, 'user_id');
    }
}

// get relations
// type of $columns is \Illuminate\Support\Collection
$relations = Analyzer::relations(User::class);

// get the first relation
$relation = $relations->first();

// all relations implement the Arrayable interface
$relation->toArray();
// [
//     'relatedClass' => User::class,
//     'type' => \Illuminate\Database\Eloquent\Relations\BelongsTo::class,
//     'foreignKey' => 'parent_id',
//     'ownerKey' => 'id',
//     'methodName' => 'parent',
// ]

RelationMethod类将所有不在类上存在的调用直接转发到底层的ReflectionMethod类。

获取模型的所有列

// CreateUserTable.php
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->json('bio')->nullable();
    });
}

// get columns
// type of $columns is \Illuminate\Support\Collection
$columns = Analyzer::columns(User::class);

// get a single column by column name
$column = $columns->get('name');

// all columns implement the Arrayable interface
$column->toArray();
// [
//     'name' => 'name',
//     'type' => \Doctrine\DBAL\Types\StringType::class,
//     'unsigned' => false,
//     'unique' => false,
//     'isForeignKey' => false,
//     'nullable' => false,
//     'autoincrement' => false,
// ]

Column类将所有不在类上存在的调用直接转发到底层的DBAL\Schema\Column类。

测试

使用以下命令运行测试

vendor/bin/phpunit

变更日志

请参阅CHANGELOG以获取有关最近更改的更多信息。

贡献

请参阅CONTRIBUTING以获取详细信息。

安全

如果你发现任何安全问题,请通过电子邮件krishan.koenig@googlemail.com联系,而不是使用问题跟踪器。

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。