Laravel 5 创建时枚举类型失败

Laravel 5 enum type fails while creating

这里的问题真的很奇怪。我正在通过 \Console\Command 为我的网站生成一个管理员,显然在某个时候我创建了它。

$user = User::create([

    'first_name' => 'Admin',
    'last_name' => 'Inistrator',
    'phone' => '',

    'email' => $email,
    'password' => bcrypt($password),
    'role' => 'admin',
]);

我的数据库中的结果是该帐户获得了 user 角色而不是 admin,但是如果我这样做

$user = User::create([

    'first_name' => 'Admin',
    'last_name' => 'Inistrator',
    'phone' => '',

    'email' => $email,
    'password' => bcrypt($password),
    'role' => 'admin',

    ]);

$user->role = 'admin';
$user->save();

然后就可以完美运行了。我怀疑 Laravel 5 在我创建一个新帐户时做了一些奇怪的事情,这将与所有特征相关联,等等。与 User 模型相关......你怎么看?

PS : 这是我的迁移 table

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

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {

            $table->increments('id');

            $table->string('first_name');
            $table->string('last_name');
            $table->string('phone');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->enum('role', ['user', 'business', 'admin']);

            $table->rememberToken();
            $table->timestamps();

        });
    }

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

        Schema::drop('users');

    }

}

试试这个来听查询:

DB::listen(function($sql, $bindings, $time)
{
    //
});

我发现了问题。感谢 DB::getQuerylog()(我也可以使用 DB::listen,如答案中所述,我听取了查询)

查询是:

    \DB::enableQueryLog();

    $user = User::create([

        'first_name' => 'Admin',
        'last_name' => 'Inistrator',
        'phone' => '',

        'email' => $email,
        'password' => bcrypt($password),
        'role' => 'admin',

        ]);

    dd(\DB::getQueryLog());

结果是:

array:1 [
  0 => array:3 [
    "query" => "insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (?, ?, ?, ?)"
    "bindings" => array:4 [
      0 => "klklm"
      1 => "y$RUorxAp4EbN/7TvEmdk.dudBBb0dgUWhmAvRsjXgVFubhEKbaLR4K"
      2 => "2015-04-13 10:30:36"
      3 => "2015-04-13 10:30:36"
    ]
    "time" => 3.17
 ]
]

所以我意识到我的字段被忽略了。我检查了模型,发现我忘记在 $fillable

中添加字段
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'email', 'password'];

我添加了其他字段,效果很好。因此,如果有人遇到类似问题,解决方案非常简单,不要忘记填写 $fillable 数组 ;)

可能会发生两种情况,

  1. 您的 enum 值不匹配
  2. 或者您的列未添加到 $fillable 数组