Laravel 指定迁移文件创建表而不重置数据的方法
网络上许多教程建议删除旧表并重新执行迁移,或者指定特定的 database 文件路径,但这些方法往往无法奏效。
php artisan migrate:reset
php artisan migrate
这种操作会导致之前积累的数据全部丢失,显然不可接受。
经过自行探索,发现可以直接针对指定表进行创建,只需启动 Tinker 并执行相应的 up 方法即可实现。示例代码如下:
该方法要求修改 composer.json 中的自动加载配置,确保包含 database/migrations 文件夹下的文件:
....
"autoload": {
"classmap": [
"database/seeds",
"database/migrations",
"database/factories"
],
....
PS D:\phpStudy\WWW\BCCAdminV1.0> php artisan tinker
Psy Shell v0.7.2 (PHP 7.1.9 — cli) by Justin Hileman
>>> (new CreateAccessLogsTable)->up();
=> null
>>>
执行后终端返回 null,起初担心操作失败,但检查数据库后发现表已成功创建。
public function up() {
// Schema::dropIfExists('users');
Schema::create('access_logs', function (Blueprint $table) {
$table->increments('id');
$table->string('ip')->default('0')->comment('ip地址');
$table->integer('customer_id')->default('0')->comment('用户ID');
$table->string('refer_website')->default('')->comment('来源网站');
$table->string('broswer')->default('')->comment('客户端浏览器');
$table->string('operating_system')->default('')->comment('客户端操作系统');
$table->string('resolution')->default('')->comment('客户端分辨率');
$table->string('visited_page')->default('')->comment('被访问的页面');
$table->timestamp('created_at');
$table->timestamp('left_at');
});
}
批量生成假数据:
https://www.jb51.net/article/171449.htm
以上这篇 Laravel 创建指定表 migrate 的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。