如何在Laravel中数据库种子JSON字段?

时间:2019-07-26 11:13:11

标签: php json laravel

我无法从JSON类型的用户表中播种user_preference列。当我输入php artisan db:seed时,我的git bash中出现错误“数组到字符串转换”。

UserSeeder.php

public function run()
{
    $faker = Faker\Factory::create();
    foreach ($this->getUsers() as $userObject) {
        $user = DB::table('users')->insertGetId([
            "first_name" => $userObject->first_name,
            "last_name" => $userObject->last_name,
            "email" => $userObject->email,
            "email_verified_at" => Carbon::now(),
            "password" => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
            "city" => 'Beograd',

            'user_preferences' => [
                $faker->randomElement(["house", "flat", "apartment", "room", "shop", "lot", "garage"])
            ],

            "created_at" => Carbon::now(),
            "updated_at" => Carbon::now(),
            "type" => 'personal',
        ]);
}

用户表

Schema::table('users', function (Blueprint $table) {
    $table->json('user_preferences')->nullable()->after('city');
});

用户模型

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use EntrustUserTrait;

    protected $fillable = [
        'first_name', 'last_name', 'email', 'password',
        'city', 'user_preferences', 'active', 'type'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'user_preferences' => 'array',
    ];
}

1 个答案:

答案 0 :(得分:2)

您忘记了将其编码为json。因此,您正在尝试插入一个数组。 它尝试将数组序列化为字符串,这是行不通的。

'user_preferences' => json_encode([
     $faker->randomElement(
          [
            "house",
            "flat", 
            "apartment", 
            "room", "shop", 
            "lot", "garage"
          ]
       )
  ]),