gpt4 book ai didi

mysql - AdonisJs Mysql 关系无法正常工作!每当我尝试从数据库中获取时都给出空数组

转载 作者:行者123 更新时间:2023-11-29 16:07:25 25 4
gpt4 key购买 nike

目前我正在学习AdonisJs和Mysql。我正在练习演示试点项目,例如 Facebook 状态/评论系统。同时我也在尝试了解mysql数据库的关系。但是每当我想要获取与某一特定状态相关的所有评论时,状态 Controller 就会生成空的评论数组。我不知道问题到底出在哪里。

这是我的状态模型

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

这是我的状态 Controller

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 指定为字符串,模型将其定义为整数。所以没有匹配到。将评论表中的值更改为整数解决了问题。

关于mysql - AdonisJs Mysql 关系无法正常工作!每当我尝试从数据库中获取时都给出空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55607039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com