【问题标题】:Laravel Eloquent not getting attribute set by defaultLaravel Eloquent 默认没有设置属性
【发布时间】:2016-11-12 19:19:49
【问题描述】:

我的 Eloquent 迁移包含一个列的默认值,并且该默认值确实是在创建模型时在数据库中设置的。但是,Eloquent 似乎不知道这个值并返回 null。

迁移:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
       $table->increments('id');
       $table->string('name');
       $table->string('email')->unique();
       $table->string('password');
       $table->integer('role')->default(0);
       $table->rememberToken();
       $table->timestamps();
    });
}

在数据库中,role 的值确实为 0,但在调用 $user->getAttributes() 时,role 列甚至都不存在(可能是因为不知何故将该值设置为 null)。

我缺少什么来完成这项工作?如何正确设置实际可用的默认值?

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-5.2


    【解决方案1】:

    我只能猜测,但我认为您还为您的 User 模型创建了 role 关系,这就是您获得 null 的原因。你不应该对列和关系使用相同的名称,如果任何字段实际上是其他表的外键,你应该为这个表的主键添加后缀,所以例如这里建议使用:

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
           $table->increments('id');
           $table->string('name');
           $table->string('email')->unique();
           $table->string('password');
           $table->unsignedInterger('role_id')->nullable()->default(null);
           $table->rememberToken();
           $table->timestamps();
        });
    }
    

    正如您在上面看到的,可以在此处对此列类型进行一些额外的更改。

    【讨论】:

    • 其实我还没有建立任何关系。除了artisan make:auth 并将这个字段添加到迁移中之外,我在全新安装 laravel 之后实际上什么也没做。
    【解决方案2】:

    如果您使用默认的 Laravel 用户迁移和模型,请在您的用户模型中添加“角色”列作为批量分配

    protected $fillable = ['name', 'email', 'password', 'role'];
    

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      相关资源
      最近更新 更多