naoray / eloquent-model-analyzer
提供一些有用的方法,以获取有关Eloquent模型类的更多信息。
v4.0.0
2023-02-20 17:07 UTC
Requires
- doctrine/dbal: ^2.6|^3.0
- illuminate/database: ^8.40.0|^9.0|^10.0
- illuminate/support: ^8.24.0|^9.0|^10.0
Requires (Dev)
- orchestra/testbench: ^6.0|^7.0|^8.0
This package is auto-updated.
Last update: 2024-09-20 20:21:18 UTC
README
分析Eloquent模型的关系和列可能会让人感到不知所措。这个小库旨在使其尽可能简单。
你可能想知道为什么你需要在运行时分析你的模型?!我能想到的所有场景都与分析代码库以生成一些代码片段有关。以下是一些可能用到的情况
- 自动为你的模型创建工厂,如laravel-prefill-factory或factory-generator中所示
- 可以用来创建类似laravel-shift/blueprint中的
trace
命令的东西
安装
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)。请参阅许可证文件以获取更多信息。