目前我正在学习AdonisJs和Mysql。我正在练习演示试点项目,如Facebook状态/评论系统。同时,我试图理解mysql数据库的关系。但是每当我想获取与一个特定状态关联的所有注释时,状态控制器都会生成空注释数组。我不知道问题到底在哪里。
这是我的状态模型
const Model = use('Model')
class Status extends Model {
comments() {
return this.hasMany('App/Models/Comment', 'id', 'status_id')
}
}
这是我的评论模型
class Comment extends Model {
users() {
return this.belongsTo('App/Models/User')
}
}
这是我的状态控制器
const Status = use('App/Models/Status')
const Comment = use('App/Models/Comment')
class StatusController {
async showAll({ request, response }){
return await Status.query()
.with('comments')
.fetch()
//return Comment.query().fetch()
}
async addStatus({ request, response, auth }) {
let data = request.all()
const user_id = await auth.user.id
data.user_id = user_id
const status = await Status.create(data)
return status
}
async addComments({ request, response }){}
}
module.exports = StatusController
statusController showAll 方法返回如下输出:(注释数组在不应该为空的地方为空(
[
{
"id": 1,
"user_id": "2",
"status": "Hello Everyone ...",
"created_at": "2019-04-09 17:05:01",
"updated_at": "2019-04-09 17:05:01",
"comments": []
}
]
出现此问题只是因为我在编写迁移时犯了一个小错误......迁移和我的数据库中的数据类型不匹配。
我在注释表中将我的状态 ID 指定为字符串,其中模型将其定义为整数。所以它不匹配。将注释表中的整数更改为整数解决了该问题。