gpt4 book ai didi

php - laravel seeder 根据数据库中的现有数据在列中分配一个值

转载 作者:行者123 更新时间:2023-11-29 07:17:09 25 4
gpt4 key购买 nike

我有一个包含 parent_id 字段的 users 表,我想播种,但我的问题是我希望 parent_id 列有基于同一个表 users 的值。我想要基于 users 表中的 role = 3parent_id 我怎样才能实现这一点? users 和 students 表是一样的。它仅在 roles 列中重要。

表结构

+-------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(191) | NO | | NULL | |
| fname | varchar(191) | NO | | | |
| lname | varchar(191) | NO | | | |
| email | varchar(191) | NO | UNI | NULL | |
| password | varchar(191) | NO | | NULL | |
| role | int(11) | NO | | 0 | |
| school_id | int(11) | NO | | NULL | |
| student_school_id | varchar(191) | YES | | NULL | |
| student_card_no | varchar(191) | YES | | NULL | |
| section_id | int(11) | YES | | NULL | |
| parent_id | int(11) | NO | | 0 | |
| gender | int(11) | NO | | 1 | |
| birthdate | date | YES | | NULL | |
| address | varchar(191) | NO | | | |
+-------------------+------------------+------+-----+---------+----------------+

我的播种机

    $faker = \Faker\Factory::create();
$numberOfStudents = $faker->numberBetween(0, 5);

for($i = 0; $i < $numberOfStudents; $i++)
{
User::firstOrCreate([
'name' => $faker->name,
'student_school_id' => $faker->unique()->numberBetween(1, 1000),
'student_card_no' => $faker->unique()->numberBetween(1, 1000),
'email' => $faker->email,
'parent_id' => // I want the expression (random user_id where role = 3)
'password' => bcrypt('ggness'),
'school_id' => 1,
'role' => 4,
'confirmed' => 1
]);
}

最佳答案

获取所有家长 ID 的列表,然后从该列表中为每个学生随机选择一个:

//an array of all parents' ids
$parent_ids=User::where('role',3)->pluck('id');

$faker = \Faker\Factory::create();
$numberOfStudents = $faker->numberBetween(0, 5);

for($i = 0; $i < $numberOfStudents; $i++)
{
User::firstOrCreate([
'name' => $faker->name,
'student_school_id' => $faker->unique()->numberBetween(1, 1000),
'student_card_no' => $faker->unique()->numberBetween(1, 1000),
'email' => $faker->email,
'parent_id' => $faker->randomElement($parent_ids),
'password' => bcrypt('ggness'),
'school_id' => 1,
'role' => 4,
'confirmed' => 1
]);
}

关于php - laravel seeder 根据数据库中的现有数据在列中分配一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58618213/

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