gpt4 book ai didi

php - 如何在 Laravel 中为 JSON 字段添加数据库种子?

转载 作者:搜寻专家 更新时间:2023-10-31 20:56:56 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于php - 如何在 Laravel 中为 JSON 字段添加数据库种子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com