Laravel播种 - 独特的用户和教师ID对

时间:2015-10-29 22:48:42

标签: php laravel laravel-5.1 laravel-migrations laravel-seeding

我在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个教师关系: 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'

如您所见,***(唯一属性)导致错误。 有没有办法解决它?你有什么想法?

2 个答案:

答案 0 :(得分:1)

您可以获得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(),
    ]);
}

答案 1 :(得分:-1)

/**@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]
    ];  
}