Search code examples
javascriptmany-to-manyknex.jsadonis.jslucid

Adonis 5 how to get pivot_column from $extras and inject into preload


I created an extra column on my manyToMany decorator and know how to preload my data based on its value. my question is how can I actually take that value and insert it to it's relevant preloaded data or insert them into a new array on parent model, in other words how can I bring back the extra pivot_column with my record(s) because currently it's in the $extra and not showing up with other properties in api call, Im currently creating a new array and inserting it with a map() but Im very worried about this approach.

thank you


Solution

  • so assuming we have a products table in manyToMany relation with colors table

    export default class Product extends BaseModel {
    @manyToMany(() => Color, {
    pivotTable: 'color_products',
    pivotTimestamps: true,
    pivotColumns: ['stock'],
    })
    public colors: ManyToMany<typeof Color>
    } 
    

    when we bring back a single instance with product.load() or an array with Product.preload()

    there will be and array of colors as a product parameter and pivot_table here color_products data in $extras I asked how can I bring the $extras as a product parameter but that was a mistake and the stock(number) is about the color of product for example a I want to know how many green shirts is in the database, as a result the solution will do just that,bringing stock number with each color object as a product parameter.here is how:

    export default class Color extends BaseModel {
    @manyToMany(() => Product, {
    pivotTable: 'color_products',
    pivotTimestamps: true,
    pivotColumns: ['stock'],
    })
    public products: ManyToMany<typeof Product>
    
    @computed()
    public get stock() {
      const stock = this.$extras.pivot_stock
      return stock
      }
    }
    

    Short version

    define a computed method on the related model and return the column from this.$extras:

        @computed()
    public get stock() {
      const stock = this.$extras.pivot_stock //my pivot column name was "stock"
      return stock
      }
    

    don't forget you should have allready have this in @manyToMany options inside your model:

    pivotColumns: ['stock'],
    

    or bring the pivotColumn from other ways.