0

I have an issue with the seeder news. It has a relationship between 2 entities. The result of the command php artisan db:seed is the next:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1364 Fi eld 'user_id' doesn't have a default value (SQL: insert into news (title, b ody, author, created_at, updated_at) values (Dr., Nisi quia et provident expedita voluptatem debitis quas. Ut in dicta magni voluptatum hic facere adipis ci. Eum aut porro voluptatem est sit numquam ex a., Janiya Lowe, 2019-09-19 06:5 4:25, 2019-09-19 06:54:25))

I have 3 entities:

User                          News                             Category
id                             id                                id                                              
                              user_id                         
                              category_id                                                                    

My NewsTableSeeder is the next:

public function run()
    {
        factory(News::class, 20)->create()->each(function ($news) {
            $news->category()->save(factory(NewsCategory::class)->make());
            $news->writtenBy()->save(factory(User::class)->make());
        });
    }

My class News is the next

class News extends Model
{
    protected $table = 'news';
    protected $fillable = ['title', 'body', 'author', 'created_at', 'update_at'];

    /**
     * WrittenBy belongs to User.
     */
    public function writtenBy()
    {
        return $this->hasOne(User::class);
    }

    /**
     * Category belongs to User.
     */
    public function category()
    {
        return $this->hasOne(NewsCategory::class);
    }
}

Could you help me please?

Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49

1 Answers1

0

Check This,

public function run()
    {
 DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        factory(News::class, 20)->create()->each(function ($news) {
            $news->category()->save(factory(NewsCategory::class)->make());
            $news->writtenBy()->save(factory(User::class)->make());
        });
 DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
albus_severus
  • 3,626
  • 1
  • 13
  • 25
  • hi @smzihan, if you could explain what is the changes and why it was put there. that would be splendid. – Bagus Tesa Sep 19 '19 at 07:14
  • In news table user_id is foreign key. So When you insert data then set FOREIGN_KEY_CHECK is zero...after inserting data it's set FOREIGN_KEY_CHECK.Its because not to check foreign_key this time – albus_severus Sep 19 '19 at 07:20
  • Thx for your answer but the result is the same. My table user and newscategory is not empty – carlos sierra garcia Sep 19 '19 at 07:48