rorecek / laravel-autoincrement
在您的 Laravel 应用程序中设置表的 AUTO_INCREMENT 值
Requires
- php: ^7.1|^8.0
- laravel/framework: ^5.5|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
README
此包将帮助您在 Laravel 应用程序中设置表的 AUTO_INCREMENT 值。
为什么需要更改自动递增值?
如果您不更改表的自动递增值,您就会暴露数据库中记录的数量。想象一下,某个用户下了一个订单并跳转到了这个订单详情 URL https://example.com/orders/10
。用户就会知道整个系统中只有 10 个订单,这可能是您不想分享的信息。如果您将表更改为从更高的自动递增数字开始,例如 512322,它就不会那么明显(https://example.com/orders/512332
)。
但如果他在一个月后再次下订单呢?这些数字之间将只有很小的差异,任何人都可以轻松计算出您的月度活动。有一个简单的解决方案。将自动递增更新添加到 Laravel 的命令调度器中,并在每小时、每天、每月等基础上自动向下一个自动递增 ID 添加一些随机数。
有哪些好处?
-
整数值比 UUID 或其他类型的字符串 ID 效率更高
-
按 ID 排序仍然会导致按时间顺序排列
-
您不会暴露数据库中资源总数,例如
https://example.com/users/10
安装
您可以使用以下命令通过 composer 安装此包
composer require rorecek/laravel-autoincrement
使用
您可以使用此包将下一个自动递增 ID 设置为特定值,或将数字添加到当前值,或将自动递增重置为最低可能值。
AutoIncrement::table('items')->set(100); // Set table auto-increment value to 100 AutoIncrement::table('items')->add(500); // Increase current auto-increment value by 500 AutoIncrement::table('items')->addRandomBetween(10, 100); // Increase current auto-increment value by random number between 10 and 100 AutoIncrement::table('items')->reset(); // Reset auto-increment to the lowest value possible taking existing records in consideration.
迁移
直接在迁移中设置自动递增。
Schema::create('items', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); AutoIncrement::table('items')->set(101); // Next auto-increment id will be 101
调度器
使用任务调度器设置自动自动递增增加。
// App\Console\Kernel.php protected function schedule(Schedule $schedule) { $schedule->call(function () { AutoIncrement::table('messages')->add(35); })->hourly(); $schedule->call(function () { AutoIncrement::table('registrations')->addRandomBetween(10, 100); AutoIncrement::table('bookings')->addRandomBetween(100, 500); })->daily(); }
高级使用
如果需要,您可以可选地使用不同的连接和/或闭包。
AutoIncrement::connection('foo')->table('items')->... // Using different connection AutoIncrement::table('items')->set(function () { return (int) date('ymd') . 1001; }); // Using closure
支持
如果您认为您发现了问题,请使用 GitHub 问题跟踪器 报告,或者更好的是,分支仓库并提交一个 pull request。
如果您正在使用此包,我很乐意听听您的想法。谢谢!
许可
MIT 许可证 (MIT)。 Pavel Rorecek