【问题标题】:Return data using relation in adonisjs is null在adonisjs中使用关系返回数据为空
【发布时间】:2020-01-30 11:11:18
【问题描述】:

我想使用 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()
        })
     }
...

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

【问题讨论】:

  • 能否请您分享产品和购物车表的架构。
  • 我已经添加了我的架构@RajeevRadhakrishnan

标签: mysql node.js database-relations adonis.js


【解决方案1】:

根据您的架构,从 Cart 模型到 Product 的关系是 belongsTo

根据您的架构,product 表的主键是 idcart 表上的引用键是 id_product

cart 模型上为product 配置您的关系,如下所示。

product() {
    return this.belongsTo("App/Models/Product", "id_product", "id");
}

使用以下产品获取购物车

const cart = await Cart.query()
      .with("product")
      .fetch();

【讨论】:

    【解决方案2】:

    当您在 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()
          })
        }
    ...
    

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 2018-11-03
      • 2017-01-29
      • 2021-11-02
      • 2021-09-08
      相关资源
      最近更新 更多