在laravel中与模型工厂建立多对多关系-列不能为空错误 [英] Seeding many-to-many relationship with model factory in laravel - column cannot be null error
问题描述
鉴于我有以下表格:
- 用户
- 问题
- 标签
- question_tag
my pivot table with two fields: question_id & tag_id
- users
- questions
- tags
- question_tag
my pivot table with two fields: question_id & tag_id
这些是我的模型关系:
用户
public function questions()
{
return $this->hasMany(Question::class);
}
问题
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
标记
public function questions()
{
return $this->belongsToMany(Question::class);
}
我已经为每种模型正确设置了数据库模型工厂.
I have setup the database model factory correctly for each models.
使用播种机,这是我要实现的目标:
With my seeder, here's what I am trying to achieve:
- 种子10个虚拟用户
- 为每个虚拟用户播种10个虚拟问题
- 对于每个虚拟问题,将其与最多5个随机标签相关联
为了实现上述三个目标,我编写了以下数据库种子器:
To achieve the above three goals, I wrote the following database seeder:
// Seed dummy users
factory(App\User::class, 10)->create()->each(function($user)
{
// With dummy questions
$user->questions()->saveMany(factory(App\Question::class, 10)->make()->each(function($question)
{
// With dummy tags
$question->tags()->sync(factory(App\Tag::class, 5)->make());
}));
});
运行时,出现以下错误:
When this runs, I am getting the following error:
[Illuminate \ Database \ QueryException] SQLSTATE [23000]:完整性 违反约束:1048列'question_id'不能为null(SQL:i 插入
question_tag
(question_id
,tag_id
)值(,1))
[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'question_id' cannot be null (SQL: i nsert into
question_tag
(question_id
,tag_id
) values (, 1))
[PDOException] SQLSTATE [23000]:违反完整性约束: 1048'question_id'列不能为空
[PDOException] SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'question_id' cannot be null
在通过数据库模型工厂创建记录的同时,如何为数据透视表添加种子?
How do you seed a pivot table, whilst creating records via the database model factory?
这个问题与我问的另一个问题相关-但是现在我遇到了另一个错误.
This question is related to another question I asked - but now I am getting a different error.
推荐答案
我已经解决了这个问题:
I've solved it like this:
<?php
use Illuminate\Database\Seeder;
class DummyDataSeeder extends Seeder
{
public function run()
{
// Seed dummy tags
factory(App\Tag::class, 10)->create();
$tagIds = DB::table('tags')->pluck('id')->toArray();
// Seed dummy users
factory(App\User::class, 10)->create()->each(function($user) use($tagIds)
{
// With dummy questions
$user->questions()->saveMany(factory(App\Question::class, 3)
->create(['user_id' => $user->id])->each(function($question) use($tagIds)
{
// With dummy tags
$question->tags()->sync(array_random($tagIds, mt_rand(1, 5)));
}));
});
}
}
也许有更好的方法可以做到这一点;但这对我有用.
这篇关于在laravel中与模型工厂建立多对多关系-列不能为空错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!