【问题标题】:Adding fields to User Eloquent ORM model将字段添加到 User Eloquent ORM 模型
【发布时间】:2015-05-16 05:36:27
【问题描述】:

我想扩展 Laravel 5.0 中现有的 User 模型以向表中添加新列。我该怎么做?

【问题讨论】:

  • 只需在数据库中添加列。手动或使用 @jszobody 建议的 Laravel 模式构建器(和迁移)
  • @justadev 如果您对我在下面的回答感到满意,请接受 :)

标签: laravel orm eloquent


【解决方案1】:
  1. 通过运行命令创建migration:
php artisan make:migration users_disabled_column

其中disabled 是您要添加到现有表的列的名称。

  1. 使用adding column 编辑新迁移,示例如下:
<?php

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

class UsersDisabledColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function($table) {
            $table->boolean('disabled')->default(false);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function($table) {
            $table->dropColumn('disabled');
        });
    }
}
  1. 执行创建的迁移:

php artisan migrate

  1. 现在您可以使用新列:
$user = User::find($id);
$user->disabled = false;
$user->save();

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 2018-09-13
    • 1970-01-01
    • 2014-09-15
    • 2018-11-01
    • 2015-10-29
    • 1970-01-01
    • 2016-11-04
    • 2018-08-03
    相关资源
    最近更新 更多