首页 > 解决方案 > 在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()
        })
     }
...

上面的数据产品为空。这段代码有什么问题?

标签: mysqlnode.jsdatabase-relationsadonis.js

解决方案


由于在 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()
      })
    }
...

推荐阅读