"Unlocking the potential of Adonis 5: Extracting the pivot_column from $extras and seamlessly integrating it

I have made a modification to my manyToMany decorator by adding an extra column. I now know how to preload data based on the value of this extra column. My question is, how can I retrieve that value and incorporate it into its corresponding preloaded data, or insert them into a new array within the parent model? In other words, how can I include the additional pivot_column with my record(s) as it is currently only accessible in $extra and not appearing alongside other properties in the API call? Currently, I am creating a new array and inserting it using map(), but I am unsure about the effectiveness of this approach.

Thank you.

Answer №1

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.

Answer №2

If you find yourself in this situation, be sure to check out this helpful resource on Additional pivot columns

Answer №3

To serialize the $extras object, you can add a specific property to the model.

class Post extends BaseModel {
  /**
   * Serialize the `$extras` object directly
   */
  public serializeExtras = true
}

If you want to customize which properties to select from the extras object, you can define the serializeExtras property as a function.

class Post extends BaseModel {
  public serializeExtras() {
    return {
      category: {
        name: this.$extras.category_name
      },
    }
  }
}

More information can be found at:

Answer №4

Instead of creating a new array, you can simply extend the query() instance using map():

      const rewards = await user.related('rewards').query()

      const transformed = rewards.map((reward) => {
        return {...reward.toJSON(), status: reward.$extras.pivot_status}
      })
      
      return response.json({data: transformed})

Unfortunately, pagination is still missing in this approach, but it gets the job done for now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating Nunjucks into an Express Application

My Node app previously used Swig as the view engine, but since it's been deprecated, I'm attempting to switch over to Nunjucks. However, after configuring Nunjucks according to the documentation, I am running into runtime errors when trying to lo ...

Error message in MS Edge API: 'browser has not been defined'

I'm currently in the process of developing an extension for the new Microsoft Edge browser. Upon loading the unpacked extension, I encountered the following error: Uncaught ReferenceError: browser is not defined According to the Microsoft Edge docu ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Is it necessary to insert a thread sleep in HtmlUnit before clicking a button?

I have been experimenting with HtmlUnit to extract scores from the BBC Sports website Upon loading the page, it initially displays Premier League scores. To view scores for other leagues, one must use a dropdown menu and click the 'Update' butto ...

Creating arrays in JavaScript or jQuery is as simple as it is in Python

newArray = [arr[p2][item] for (item in subarray)] Is there a way to achieve a similar shortcut in JavaScript or with the help of jQuery without explicitly looping and adding elements to an array? This would allow me to perform additional calculations usi ...

What is the reason behind ASP MVC model binder's preference for JSON in POST requests?

Is there a way to bind data to a model when sending a 'GET' request with JSON.stringify() using AJAX? Currently, the model value is always null when using 'GET', but it works fine with 'POST'. Are there any solutions for this ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

Save this text in HTML format to the clipboard without including any styling

When using this code to copy a htmlLink to the clipboard: htmlLink = "<a href='#'>link</a>"; var copyDiv = document.createElement('div'); copyDiv.contentEditable = true; document.body.appendChild(copyDiv); ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

Toggle between input and span values within a row in an AngularJS table

I have the following HTML code where I need to toggle between input and span fields within a table row. <table> <tbody ng-repeat="(i, cont) in char.items"> <tr> <td> <div> <a ng-click="choose()"> <in ...

Tips for incorporating a clickable link or dialog box into a Backbone.js JST EJS file

I'm looking to integrate a modal dialog box (by simply clicking OK) within a Backbone.js template file. This specific scenario involves iterating through a loop structure, as shown in show_template.jst.ejs: <% for(var i = 0... all words %> < ...

Having Trouble with QR Code Generator Functionality

UPDATE: The initial code has been updated to implement the recommendations provided. I am currently working on a QR Code generator that updates every minute. Although I have developed the code below, I am encountering some errors and could use some assist ...

Is it possible to develop an asynchronous function using Javascript?

Take a look at this code snippet: <a href="#" id="link">Link</a> <span>Moving</span> $('#link').click(function () { console.log("Enter"); $('#link').animate({ width: 200 }, 2000, function() { c ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

Should I convert to an image or utilize the canvas?

I'm debating whether it's more efficient to convert a canvas drawing into an image before inserting it into the DOM, or if it's better to simply add the canvas itself. My method involves utilizing canvas to generate the image. ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

"Looping through a list but skipping over a certain element in

Currently, I am utilizing AngularJS to display multiple elements in my HTML code. While Angular is successfully repeating the divs as intended, there seems to be an issue when trying to repeat a specific div. More details provided below: <tr ng-repeat= ...

What is the best way to access and verify data from an array that has been passed through props

I am working with a component that takes an array as a prop <Component runners={['1','2']}/> Inside this functional component, my goal is to generate an element for each value in the array. Here's my logic: const { runners ...

What is the best way to keep a text editable in a razor editor without it vanishing?

I'm on a quest to find the name for a certain functionality that has been eluding me, and it's truly driving me up the wall. Check out the razor code snippet I've been using to exhibit my form inputs: <div class="col-sm"> ...

Promise rejection not caught: ; Zone: angular ; Task:

While using meteor and trying to set up a (click) attribute, I encountered the following error message. https://i.sstatic.net/Qzk9T.png This is my code: import { Component, NgZone, AfterContentInit } from 'angular2/core'; import { NgIf, NgFor ...