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.