数据库
首页 > 数据库> > laravel11怎么把用户表字段email_verified_at移到别一张表上?

laravel11怎么把用户表字段email_verified_at移到别一张表上?

作者:互联网

在Laravel中,如果您想将用户表的email_verified_at字段移到另一张表,可以按照以下步骤操作:

1. 创建副表的迁移

首先,您需要创建一个新的迁移文件,来创建存放email_verified_at的副表。您可以通过 Artisan 命令生成迁移:

php artisan make:migration create_user_email_verifications_table

Bash

然后在生成的迁移文件中,定义副表结构:

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

class CreateUserEmailVerificationsTable extends Migration
{
    public function up()
    {
        Schema::create('user_email_verifications', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamp('email_verified_at')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('user_email_verifications');
    }
}

PHP

2. 执行迁移

运行迁移以创建新的副表:

php artisan migrate

Bash

3. 转移email_verified_at数据

接下来,您需要将现有的email_verified_at数据从用户表插入到新的副表中。您可以创建一个新的迁移或使用Laravel的tinker工具。这里以迁移为例:

php artisan make:migration transfer_email_verified_at_data

Bash

在迁移文件中,添加转移数据的逻辑:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class TransferEmailVerifiedAtData extends Migration
{
    public function up()
    {
        $users = DB::table('users')->select('id', 'email_verified_at')->get();

        foreach ($users as $user) {
            DB::table('user_email_verifications')->insert([
                'user_id' => $user->id,
                'email_verified_at' => $user->email_verified_at,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    public function down()
    {
        DB::table('user_email_verifications')->truncate();
    }
}

PHP

然后运行迁移:

php artisan migrate

Bash

4. 删除用户表中的email_verified_at字段

最后,您可以移除用户表中的email_verified_at字段。创建另一个迁移:

php artisan make:migration remove_email_verified_at_from_users_table

Bash

在迁移文件中,添加以下代码:

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

class RemoveEmailVerifiedAtFromUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('email_verified_at');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('email_verified_at')->nullable();
        });
    }
}

PHP

运行迁移:

php artisan migrate

Bash

5. 更新模型关系

最后,在User模型和UserEmailVerification模型中设置关系:

User模型中:

public function emailVerification()
{
    return $this->hasOne(UserEmailVerification::class);
}

PHP

UserEmailVerification模型中:

public function user()
{
    return $this->belongsTo(User::class);
}

PHP

这样,您就完成了将email_verified_at字段移到另一张表的操作。

标签:
来源: