如何在Laravel中对JSON字段进行数据库填充?

9

我在尝试从用户表中的JSON类型的user_preference列进行种子填充,但在使用php artisan db:seed命令时,在我的Git Bash中出现了“Array to string conversion”错误。

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',
    ];
}

4
你能否不使用json_encode将那个数组包装起来? - Jonnix
@Jonnix 我真是太蠢了,没错,它可以工作。 :) 把它发布为答案。 - mrmar
2个回答

12

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

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

5
在 Laravel 8 中,您可以像这样使用它:
'user_preferences' => [
   $faker->randomElement(
      [
        'house',
        'flat', 
        'apartment', 
        'room', 'shop', 
        'lot', 'garage'
      ]
   )
],

注意:无需对其进行json_encode
当然,不要忘记将此放入您的模型中。
/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'user_preferences' => 'array'
];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接