Php 在Laravel中使用种子填充数据库列时出现问题
我需要从种子填充数据库列。我在user_profiles表中有“Interest_in”列,我需要使用user_interests表中“value_id”列中的相应id填充它。用户配置文件和用户兴趣表都连接到用户表(“用户id”列在两个表中)。因此,如果'value_id'列的值为1,则在'interest_in'列中必须为1,我需要有关如何从seeders填充该'interest_in'列的帮助“值\u id”列已填充。这里是我的表和示例数据以及我的代码,但它目前无法工作,它显示了“数组到字符串转换”错误 用户兴趣表Php 在Laravel中使用种子填充数据库列时出现问题,php,laravel,laravel-seeding,Php,Laravel,Laravel Seeding,我需要从种子填充数据库列。我在user_profiles表中有“Interest_in”列,我需要使用user_interests表中“value_id”列中的相应id填充它。用户配置文件和用户兴趣表都连接到用户表(“用户id”列在两个表中)。因此,如果'value_id'列的值为1,则在'interest_in'列中必须为1,我需要有关如何从seeders填充该'interest_in'列的帮助“值\u id”列已填充。这里是我的表和示例数据以及我的代码,但它目前无法工作,它显示了“数组到字符
user_id field_id value_id
1 1 1
用户配置文件表
id user_id interested_in
1 1 and here needs to be 1, to associate value_id (1) from user_interests table
UserProfileTableSeeder.php
class UserProfileTableSeeder extends Seeder
{
use ChunkSeeder;
public function run()
{
$users = User::all()->pluck('id');
$user_interests = DB::table('user_interests')->select('value_id')->where('field_id', 1)->get();
$user_interests_values = $user_interests->pluck('value_id')->toArray();
$seed = [];
foreach ($users as $userId) {
$seed[] = factory(UserProfile::class)->make(
[
'user_id' => $userId,
'interested_in' => $user_interests_values, // Shows array to string error!!!
]
)->toArray();
}
$this->seedChunks($seed, [UserProfile::class, 'insert']);
}
}
这就是为什么
$user\u interests\u values
是一个数组,正如您在这一行(末尾)中看到的:
$user\u interests\u values=$user\u interests->pull('value\u id')->toArray();
请在工厂中尝试将$user\u interests\u value
更改为当前($user\u interests\u value)
或可能的$user\u interests\u value['id']
或其他任何内容
PS:我不太确定$user\u interests\u values
里面有什么,你可以通过dd()
看到它,然后运行迁移(不要担心,迁移不会成功,因为dd()
,你可以稍后再次运行它,直到它正确完成
顺便说一句,我建议您做一些比rum()
方法更清晰的事情。我的意思是,像这样的事情:
$interest=factory(UserInterests::class)->create();
工厂(UserProfiles::class,20)->创建([
“利息”=>$interest->id,
]);