在迁移文件中获取表ID(laravel 5.8)

我想要用户的 id。(在迁移中使用 if 语句中的 id 并向新表列添加不同的默认值)


我尝试使用,getColumns()->id但它在 ide 中显示了一些警告(未找到字段 id)。


<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class AddUserRoles extends Migration

{

    public function up()

    {

        Schema::table('users', function (Blueprint $table) {

            $ID = $table->getColumns()->id;



           if($ID == '1') {

               $table->string('role')->default('admin');

               } else {

                 $table->string('role')->default('member');

        });

    }



    public function down()

    {

        Schema::table...

              .....

    }

}

编辑:这是用户表



class CreateUsersTable extends Migration

{

    public function up()

    {

        Schema::create('users', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('name');

            $table->string('email')->unique();

            $table->timestamp('email_verified_at')->nullable();

            $table->string('password');

            $table->rememberToken();

            $table->timestamps();

        });

    }

我的目的是使用 id 为 users 表设置不同的默认角色。


弑天下
浏览 125回答 1
1回答

拉风的咖菲猫

在创建 users 表时您无法读取用户,因为您还没有任何用户。为用户创建此表:class CreateUsersTable extends Migration{&nbsp; &nbsp; public function up()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Schema::create('users', function (Blueprint $table) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->bigIncrements('id');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->string('name');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->string('email')->unique();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->string('role')->nullable();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->timestamp('email_verified_at')->nullable();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->string('password');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->rememberToken();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->timestamps();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}然后,您可以添加用户并检查id为他们分配角色:$user = new User();$user->name = 'name';$user->email = 'email@example.com';$user->password = Hash::make("123456");$user->save();if ($user->id === $someId) {&nbsp; &nbsp; $user->role = 'some_role';&nbsp; &nbsp; $user->save();}希望能帮助到你。
打开App,查看更多内容
随时随地看视频慕课网APP