php Laravel seeding -唯一的用户和教师ID对

bbuxkriu  于 2023-11-16  发布在  PHP
关注(0)|答案(3)|浏览(161)

我在Laravel 5.1中使用数据库迁移和播种。

移民

public function up()
{
    Schema::create('teachers', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('teacher_id')->unsigned();
        $table->boolean('disable')->default(0);
        $table->timestamps();

        $table->unique(['user_id', 'teacher_id']);

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('teacher_id')->references('id')->on('users')->onDelete('cascade');
    });
}

字符串

  • user_id和teacher_id必须是唯一的。
    样板工厂
$factory->define(App\Teacher::class, function ($faker) {
    return [
        'user_id'           => $faker->numberBetween(1, 59),
        'teacher_id'        => $faker->numberBetween(1, 59),
    ];
});


我在DatabaseSeeder.php中设置了用于生成500个教师关系的seeder:factory(App\Teacher::class, 500)->create();
但我得到了这个错误:

[PDOException] 
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '10-11' for key 'teachers_user_id_teacher_id_ 
unique'


正如你所看到的,*(唯一属性)导致了这个错误。有什么方法可以修复它吗?你的想法是什么?

nbnkbykc

nbnkbykc1#

你可以得到一个User模型的集合,然后在一个while循环中从该集合中的随机ID分配对:

$users = User::all(['id']);

while ($users->count() > 1) {
    // Get random user for a teacher, and remove from collection
    $teacher = $users->random();
    $users->pull($teacher->getKey());

    // Get random user and remove from collection
    $user = $users->random();
    $users->pull($user->getKey());

    Teacher::create([
        'user_id' => $user->getKey(),
        'teacher_id' => $teacher->getKey(),
    ]);
}

字符串

yvt65v4c

yvt65v4c2#

如果数据库中存在唯一的记录,你可以抛出异常。然后在seeder类中,使用try-catch块,捕获异常不做任何事情。如果遇到现有的记录,播种应该继续。
例如:假设product_stocks表中有3列,其中product_idcolor_idsize_id是唯一的。
工厂类:

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    $productId = $this->faker->randomElement(Product::pluck('id')->toArray());
    $colorId = $this->faker->randomElement(Color::pluck('id')->toArray());
    $sizeId = $this->faker->randomElement(Size::pluck('id')->toArray());

    $exists = ProductStock::where([
        ['product_id', '=', $productId],
        ['color_id', '=', $colorId],
        ['size_id', '=', $sizeId],
    ])->exists();

    if ($exists) {
        throw new Exception('duplicate value');
    }

    return [
        'product_id' => $productId,
        'color_id' => $colorId,
        'size_id' => $sizeId,
        'stok_ready' => $this->faker->numberBetween(0, 100),
    ];
}

字符串
播种机等级:

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    try {
        ProductStock::factory()
            ->count(Product::count() * rand(5, 10))
            ->create();
    } catch (Exception $e) {
        // do something
    }
}

gajydyqb

gajydyqb3#

/**@var array $unique*/

$repeatRandom =  static function () use (&$unique, &$repeatRandom) {
    $userId = User::pluck('id')->random();
    $teacherId = User::pluck('id')->random();
    $newPair = [
        $userId, $teacherId
    ];

    foreach ($unique as $items) {
        if (!array_diff_assoc($items, $newPair)) {
            return $repeatRandom($unique);
        }
    }
    return $newPair;
};

$factory->define(Teacher::class, static function (Faker $faker) use (&$unique, &$repeatRandom) {

    $userId = User::pluck('id')->random();
    $teacherId = User::pluck('id')->random();

    $newPair = [
        $userId, $teacherId
    ];

    if (is_array($unique)) {
        foreach ($unique as $items) {
            if (!array_diff_assoc($items, $newPair)) {
                $newPair = $repeatRandom($unique);
            }
        }
    }

    $unique[]  = $newPair;
    return [
        'user_id' => $newPair[0],
        'teacher_id' => $newPair[1]
    ];  
}

字符串

相关问题