侧边栏壁纸
  • 累计撰写 168 篇文章
  • 累计创建 71 个标签
  • 累计收到 35 条评论

目 录CONTENT

文章目录

Laravel迁移在特定列教程后添加列

神兵小将
2023-02-04 / 0 评论 / 0 点赞 / 226 阅读 / 1,349 字 / 正在检测是否收录...

创建迁移文件
让我们为此考虑一个迁移文件。

在终端中打开项目并运行此命令以创建帖子表的帖子迁移文件。

$ php artisan make:migration create_posts_table

它将在/database/migrations文件夹中创建一个文件,即 xxx_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->string('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

接下来,运行此命令。

$ php artisan migrate

迁移后,它将在数据库中创建 posts 表。
1

在特定列后添加列
让我们在“正文”之后添加一个名称为“状态”的列。

返回终端并运行此命令。

$ php artisan make:migration add_new_column_posts

它将在 /database/migrations 文件夹中创建一个文件,即 xxx_add_new_column_posts.php

打开文件并将此完整代码写入其中。

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function($table){

            $table->tinyInteger('status')->after('body');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
};

接下来,运行此命令。

$ php artisan migrate

迁移后,它将更新帖子表。在正文列之后添加一个状态列到数据库表中。

2

0

评论区