首页 > 解决方案 > 具有自定义 id 类型的 Laravel 多对多工厂

问题描述

我正在使用 Laravel 8 并尝试制作数据库工厂/播种机我遇到了一些问题。

我有以下数据库架构:

Schema::create('authors', function (Blueprint $table) {
    $table->id();
    $table->string('first_name');
    $table->string('last_name');
    $table->timestamps();
});

Schema::create('books', function (Blueprint $table) {
    $table->char('isbn', 13)->unique('isbn');
    $table->string('title');
    $table->string('edition');
    $table->date('release_date');
    $table->string('image');
    $table->timestamps();
});

//Create pivot table for author since its many to many relationship.
Schema::create('author_book', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('author_id');
    $table->char('book_id', 13);
    $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
    $table->foreign('book_id')->references('isbn')->on('books')->onDelete('cascade');
});

现在我正在尝试创建工厂和数据库播种器,但使用以下行播种时出现错误:

Book::factory()
    ->has(Author::factory()->count(2))
    ->create();

这给了我以下错误:

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(`bokel`.`author_book`, CONSTRAINT `author_book_book_id_foreign` FOREIGN KEY (`book_id`) REFERENCES `books` (`isbn`) ON DELETE CASCADE)
(SQL: insert into `author_book` (`author_id`, `book_id`) values (1, 0), (2, 0))

如果我理解正确,因为 isbn 数字是预期的,但 laravel 只是将一个整数放入数据透视表中。解决这个问题的最佳方法是什么?我在想这样的事情,但这也不起作用。

Book::factory()
    ->has(Author::factory()->count(2), function (array $attributes, Book $book) {
        return ['book_id' => $book->isbn];
    })
    ->create();

工厂定义如下:

public function definition()
{
    return [
        'isbn' => $this->faker->unique()->isbn13,
        'title' => $this->faker->sentence,
        'edition' => $this->faker->numberBetween(1, 10),
        'release_date' => $this->faker->date(),
        'image' => $this->faker->imageUrl(),
    ];
}

public function definition()
{
    return [
        'first_name' => $this->faker->firstName,
        'last_name' => $this->faker->lastName
    ];
}

标签: phplaraveleloquentlaravel-factory

解决方案


正如我在评论中提到的,我认为你的问题是你的Book模型中的关系。

在您的Book模型中,您需要:

public function authors()
{
    return $this->belongsToMany(Author::class,
        'author_book', 'book_id', 'author_id', 'isbn', 'id')
        ->using(AuthorBook::class);
}

尝试这样,如果这不能解决您的问题,我将删除答案。

查看文档,并检查链接在多对多部分中有许多关系。

祝你好运!


推荐阅读