作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我无法从 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/
我是一名优秀的程序员,十分优秀!