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

mrm*_*mar 7 php json laravel

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

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',
        ]);
}
Run Code Online (Sandbox Code Playgroud)

用户表

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

用户模型

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',
    ];
}
Run Code Online (Sandbox Code Playgroud)

Ker*_*rel 8

您忘记将其编码为 json。所以你试图插入一个数组。它试图将数组序列化为字符串,但这是行不通的。

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


小智 5

在 Laravel 8 中,你可以像这样使用它:

'user_preferences' => [
   $faker->randomElement(
      [
        'house',
        'flat', 
        'apartment', 
        'room', 'shop', 
        'lot', 'garage'
      ]
   )
],
Run Code Online (Sandbox Code Playgroud)

注意:不需要json_encode

当然,不要忘记将其放入您的模型中。

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'user_preferences' => 'array'
];
Run Code Online (Sandbox Code Playgroud)