简体   繁体   中英

Return data using relation in adonisjs is null

I want to fetching data from two table that have one to one relation in database using adonisjs. When i'm try to fetch all data from one of table, that result is null.

This is my relation code in model:

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

...

This is my product's model:

class Product extends Model {

    static get table()
    {
        return 'product'
    }

    static get primaryKey()
    {
        return 'product_id'
    }

}
module.exports = Product

Then, this is my controller

async index ({response}) {
        const allProduct = await Cart.query().with('product').fetch();
        return response.json({
            status:true,
            data: allProduct
        })
    }

edited

This is my cart schema

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

And this is my product schema:

class ProductSchema extends Schema {
    async up () {
    const exists = await this.hasTable('product')

    if (!exists) {
        this.create('product', (table) => {
          table.increments()
          table.timestamps()
        })
     }
...

data product above is null. Whats wrong with this code?

you get output null due to when you put a reference in Cartschema this datatype is not a string. change datatype string to an integer like this

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

The relationship from Cart model to Product is belongsTo as per your schema.

The primary key of product table is id and reference key on cart table is id_product as per your schema.

Configure your relationship on cart model for product as follows.

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

Fetch cart with products as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM