简体   繁体   English

如何在 AdonisJs 中使用 HasMany 关系

[英]How to use HasMany Relationship in AdonisJs

I am trying to do hasMany relationship in my adonisjs project on Post and User model我正在尝试在我的 adonisjs 项目中对 Post 和 User model 做 hasMany 关系

I have a column of user_id in my database column and i have tried the below code我的数据库列中有一个user_id列,我尝试了以下代码

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在我的用户 model 但任何时候我发帖我都会得到这个ER_NO_DEFAULT_FOR_FIELD: Field 'user_id' doesn't have a default value

The user_id field in the post model cannot be null.帖子 model 中的user_id字段不能为 null。

You can set a default value in the post migration您可以在迁移后设置默认值

// every post has a default owner
table.integer('user_id').defaultTo(1)

or allow the relationship to be null或允许关系为 null

table.integer('user_id').nullable()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM