fatihirday / suffix
laravel迁移后缀表
v0.1.4
2024-08-19 12:25 UTC
Requires
- php: ^7.4|^8.0
README
安装
- 运行composer命令安装包
composer require fatihirday/suffix
- 发布配置和迁移文件。
php artisan vendor:publish --provider="Fatihirday\Suffixed\SuffixServiceProvier"
- 响应
* config/suffixed.php
* migrations/*_create_suffixes_table.php
- 要使用包中的后缀列表
php artisan migrate
如果你要使用自己的列表,可以删除文件migrations/*_create_suffixes_table.php
配置
- 配置后缀文件
return [ 'suffixes' => [ 'table' => \Fatihirday\Suffixed\Models\Suffix::class, 'column' => 'code', 'auto_create_suffixed_tables' => true, ], 'suffix_auto_check' => true, 'merge_operator' => '_', 'suffix_max_length' => 3, ];
- 后缀模型
class Suffix extends Model { use HasFactory, SuffixList; }
使用use SuffixList;
来定义自定义模型。
示例
创建迁移
1. 向后缀表插入行
php artisan tinker
$row = new \Fatihirday\Suffixed\Models\Suffix(); $row->name = 'Fatih'; $row->code = 'fth'; $row->save();
2. 创建后缀迁移
php artisan make:migration-suffix CreateDemoTable
class CreateDenemeTable extends SuffixMigration implements SuffixSchame { protected $baseTableName = 'demo'; public function upSuffix(string $tableName, string $prefix) { Schema::create($tableName, function (Blueprint $table) use ($prefix) { $table->id(); $table->string('name', 30); $table->timestamps(); }); } public function downSuffix(string $tableName, string $prefix) { Schema::dropIfExists($tableName); } }
3. 运行迁移
php artisan migrate
创建表 demo_fth
4. 创建模型
在模型中使用后缀来访问后缀表
class Demo extends Model { use HasFactory, Suffixed; }
后缀表的使用
检查后缀表
App\Models\Demo::checkSuffixCode('fth'); // Response : true || false
设置后缀代码
App\Models\Demo::setSuffixCode('fth')->toSql(); // Response : "select * from `demo_fth`"
获取后缀表名
App\Models\Demo::setSuffixCode('fth')->getTable(); // Response : "demo_fth"
获取后缀表的后缀代码
App\Models\Demo::setSuffixCode('fth')->getSuffixCode(); // Response : "fth"
示例查询
// insert row to demo_fth table $newRow = App\Models\Demo::setSuffixCode('fth'); $newRow->name = 'deneme'; $newRow->save(); // get rows to demo_fth table App\Models\Demo::setSuffixCode('fth')->whereNotNull('name')->get();