axn / laravel-models-generator
从数据库生成Eloquent模型。
6.6.0
2023-02-21 08:46 UTC
Requires
- doctrine/dbal: ^2.13 || ^3.1
- illuminate/support: ~5.8 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
README
使用数据库模式生成Eloquent模型及其关系(属于、拥有多个、拥有一个)。
安装
使用Composer安装包
composer require axn/laravel-models-generator
在Laravel 5.5中,服务提供者将自动注册。在框架的旧版本中,只需将服务提供者添加到config/app.php
中的提供者数组中。
'providers' => [ // ... Axn\ModelsGenerator\ServiceProvider::class, ],
如果需要,使用以下命令发布配置和模板(占位符)
// config php artisan vendor:publish --tag=models-generator.config // stubs php artisan vendor:publish --tag=models-generator.stubs
配置发布在config/models-generator.php
中,模板发布在resources/stubs/vendor/models-generator/
中
如果需要,修改配置选项和模板内容。
使用方法
只需运行此命令
php artisan models:generate
选项
- --table (或 -t) : 如果只想生成某些表。要选择多个表,可以这样做:-t table1 -t table2 -t ...
- --preview (或 -p) : 如果只想显示有关生成器将执行的操作的信息消息,而不接触文件。
命名约定
- 模型: 单数表名,使用大驼峰式(cf配置“singular_rules”,如果单数化不正确)。
- "拥有多个"关系: 相关表名(复数),使用小驼峰式。
- "拥有一个"关系: 相关表名(单数),使用小驼峰式
- "属于"关系: 外键名称(不带"_id"或"id_"),使用小驼峰式。
其他细节
- "拥有多个"关系: 关系名称只是模型名称的小驼峰式,因此模型名称应该是复数。
- "拥有多个"和"拥有一个"关系: 如果外键名称不是标准名称,则将精度附加到关系名称,例如"Via{nomFK}"。
示例
// "comments" table class Comment extends Model { // "belongs to" relation to "users" via "user_id" public function user() {} // "belongs to" relation to "users" via "updator_id" public function updator() {} } // "users" table class User extends Model { // "has many" relation to "comments" via "user_id" public function comments() {} // "has many" relation to "comments" via "updator_id" public function commentsViaUpdatorId() {} }