26688

Seeding many-to-many relationship with model factory in laravel - column cannot be null error

Question:

Given that I have the following tables:

<ul><li>users</li> <li>questions</li> <li>tags</li> <li>question_tag my pivot table with two fields: question_id & tag_id</li> </ul>

and these are my model relationships:

<strong>User</strong>

public function questions() { return $this->hasMany(Question::class); }

<strong>Question</strong>

public function user() { return $this->belongsTo(User::class); } public function tags() { return $this->belongsToMany(Tag::class); }

<strong>Tag</strong>

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:

<ol><li>Seed 10 dummy users</li> <li>For each dummy user, seed 10 dummy questions</li> <li>For each dummy question, associate it with up-to 5 random tags</li> </ol>

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:

<blockquote>

[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]: Integrity constraint violation: 1048 Column 'question_id' cannot be null

</blockquote>

How do you seed a pivot table, whilst creating records via the database model factory?

<hr />

This question is <a href="https://stackoverflow.com/q/46900408/2332336" rel="nofollow">related</a> to another question I asked - but now I am getting a different error.

Answer1:

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))); })); }); } }

<em>Maybe there's a better a way to do this; but this is working for me.</em>

Answer2:

When you use saveMany method, you should set Eloquent model instance as parameter like this.

$user->questions()->saveMany(factory(App\Question::class, 10)->make())->each(function($question) { // With dummy tags $question->tags()->sync(factory(App\Tag::class, 5)->make()); });

Recommend

  • Method addEagerConstraints does not exist
  • Is there a better functional way to process a vector with error checking?
  • Sharepoint Client Object Model The property or field has not been initialized
  • How to connect a renderer to a specific endpoint in a viewset, and only that endpoint
  • how can i open a webpage in a webview from a fragment with buttons?
  • How to apply CSS to document.write()?
  • How to achieve density/heat map effect in iOS (iPhone/iPad)?
  • Difference between assigning instantiation to parent class and derived class
  • In Moment.js, how do you get the date of the next occurrence of a specific month (ex: 'next Jan
  • What is the correct way to combine two UserControls into one with two states?
  • Using Autofac with AJAX-enabled WCF Service
  • Python List of Tuples (Find value with key + check if exist)
  • Vue.js 2: Vue cannot find files from /assets folder (v-for)
  • TypeError: Cannot compare type 'Timestamp' with type 'date'
  • python socket.sendto
  • Failed to resolve: firebase-auth-15.0.0 [closed]
  • How do I set the logging properties in a spring java configuration?
  • How to include WYSIWYG text editor in an HTML using google script
  • First dynamically-added TinyMCE editor displays, others do not
  • Visual Studio 2017 Professional- Unable to find package at source
  • 'Edit' function for forum posts and such
  • how do i compare two rows and store the similarities of the two rows in another column
  • Cloud Code: Creating a Parse.File from URL
  • customize soft keyboard key preview
  • Angular FormGroup won't update it's value immediately after patchValue or setValue