mysql - 在adonisjs中使用关系返回数据为空
问题描述
我想使用adonisjs从数据库中具有一对一关系的两个表中获取数据。当我尝试从一个表中获取所有数据时,该结果为空。
这是我在模型中的关系代码:
class Cart extends Model {
product () {
return this.hasOne('App/Models/Product')
}
static get table()
{
return 'cart'
}
static get primaryKey()
{
return 'id_cart'
}
static get foreignKey()
{
return 'id_product'
}
...
这是我的产品型号:
class Product extends Model {
static get table()
{
return 'product'
}
static get primaryKey()
{
return 'product_id'
}
}
module.exports = Product
然后,这是我的控制器
async index ({response}) {
const allProduct = await Cart.query().with('product').fetch();
return response.json({
status:true,
data: allProduct
})
}
已编辑
这是我的购物车架构
class CartSchema extends Schema {
async up () {
const exists = await this.hasTable('cart')
if (!exists) {
this.create('cart', (table) => {
table.increments()
table.string('id_product').unsigned().references('product_id').inTable('product')
table.timestamps()
})
}
...
这是我的产品架构:
class ProductSchema extends Schema {
async up () {
const exists = await this.hasTable('product')
if (!exists) {
this.create('product', (table) => {
table.increments()
table.timestamps()
})
}
...
上面的数据产品为空。这段代码有什么问题?
解决方案
由于在 Cartschema 中放置引用时,此数据类型不是字符串,因此您得到输出 null。将数据类型字符串更改为这样的整数
class CartSchema extends Schema {
async up () {
const exists = await this.hasTable('cart')
if (!exists) {
this.create('cart', (table) => {
table.increments()
table.integer('id_product').unsigned().references('product_id').inTable('product')
table.timestamps()
})
}
...
推荐阅读
- docker - 容器化 Spring Boot 应用程序时出现 Docker 错误
- android - 从文本观察器更改 imeOptions
- javascript - 从函数返回并在单击时重置其变量
- ios - 在 UICollectionView 中引用 UIImageView / UILabel
- tensorflow - 如果我的 RAM 不足,交换内存是否有帮助?
- charts - 在 h 轴上使用刻度选项时出现问题:谷歌图表
- android - 如何显示带有进度条的加载图像和图像也想在我的gridview andriod studio中计数
- python - Python datetime 格式化字符串转换-24 小时时间问题
- mongodb - 完全匹配优先的MongoDB聚合匹配查询
- laravel - 文件 laravel 安装本地和服务器上的差异