Let's consider a scenario where we have a products table in a many-to-many relationship with colors table
export default class Product extends BaseModel {
@manyToMany(() => Color, {
pivotTable: 'color_products',
pivotTimestamps: true,
pivotColumns: ['stock'],
})
public colors: ManyToMany<typeof Color>
}
When retrieving a single instance using product.load() or an array with Product.preload()
the returned object will contain an array of colors as well as data from the pivot_table (in this case color_products) in $extras.
I originally asked how to bring the $extras as a product parameter, but that was incorrect. The stock number represents the quantity of each color for a specific product. For example, if I want to know the quantity of green shirts in the database, the solution will provide that information by including the 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
}
}
In short,
You can define a computed method on the related model and retrieve the column value from this.$extras:
@computed()
public get stock() {
const stock = this.$extras.pivot_stock //my pivot column name was "stock"
return stock
}
Make sure you have specified the pivotColumns option in @manyToMany options within your model:
pivotColumns: ['stock'],
Alternatively, you can fetch the pivotColumn through other means.