HasMany Relationship in AdonisJs

I am trying to do hasMany relationship in my adonis project on Post and User model

I have a column of user_id in my database column and i have

posts () {
    return this.hasMany('App/Models/Post')
  }

in my user model but anytime i make a post i get this ER_NO_DEFAULT_FOR_FIELD: Field 'user_id' doesn't have a default value

Hey @heolad, can you please share your posts table migration file over here ?

@NerdyLuffy

class PostsSchema extends Schema {
  up () {
    this.create('posts', (table) => {
      table.increments()
      table.string('subject', 255).notNullable()
      table.text('body').notNullable()
      table.string('slug', 500).notNullable()
      table.string('image', 191).nullable()
      table.integer('user_id').unsigned().notNullable()
      table.timestamps()
    })
  }

  down () {
    this.drop('posts')
  }
}

Can you remove notNullable() from user_id and run the migrations and try that out ?

if i should remove notNullable the ID will not be in the table

1 Like