【问题标题】:How to database seed JSON field in Laravel?如何在 Laravel 中数据库种子 JSON 字段?
【发布时间】:2019-12-04 17:33:48
【问题描述】:

我无法从 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',
    ];
}

【问题讨论】:

  • 你不能把那个数组包装在json_encode中吗?
  • @Jonnix 我太愚蠢了,是的,它有效。 :) 将其发布为答案。

标签: php json laravel


【解决方案1】:

您忘记将其编码为 json。所以你试图插入一个数组。 它尝试将数组序列化为字符串,但不起作用。

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

【讨论】:

    【解决方案2】:

    在 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'
    ];
    

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 2015-02-04
      • 2014-11-21
      • 2014-01-24
      • 2016-07-13
      • 1970-01-01
      • 2013-09-04
      • 2017-11-27
      • 2019-08-20
      相关资源
      最近更新 更多