Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables.

I have relationships with the "items" and "comments" tables.

My approach involves selecting the top 5 items with the most comments from the "comments" table using the "GROUP BY" method. I then plan to use the "object_id" field from these items to retrieve corresponding data from the "items" table based on the ID stored in the "id" column.

In essence, I want to fetch items with the highest number of comments. However, the required data for this task resides in two separate tables: "items" and "comments."

I have already established a new route and constructor for this purpose. While I can successfully call the route and trigger the constructor, I am unsure about the specific operations needed to collect the necessary data. My database management system is MySQL.

I am contemplating whether to create a custom API within Strapi for direct frontend access or to make multiple API calls from the frontend itself. Although I understand how to write queries across multiple tables to obtain the desired results, I need guidance on incorporating the query into Strapi for creating a custom API route.

Your assistance is greatly appreciated. Thank you!

Answer №1

One of Strapi's key features is its utilization of Knex.js as an internal query builder. This allows users to perform MySQL operations in a more JavaScript-oriented manner using the functionalities provided by Knex.js.

If you're interested in learning how to use Knex.js, you can refer to the official documentation.

To incorporate Knex.js into Strapi, you can follow this example within a controller or service:

const knex = strapi.strapi.db.connection.raw;

const data = await knex.select('*').from('data_table_name'); // or execute any other desired query operation

For further insights on utilizing Knex.js with Strapi, you may want to check out responses to this question.

We hope this information proves helpful!

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

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this. Here's what I'm currently seeing: You are not getti ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

Ways to modify the default text in a dropdown menu?

I'm currently attempting to modify the title of a dropdown using the Multi-select plugin found here. However, I've encountered an issue where I am unable to dynamically change the text (Dropdown title) of the dropdown using JavaScript. $(' ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

Updates in dropdown events when options data has been modified

Hey there, I'm wondering about dropdown events. Let's say I have two dropdowns. When a selection is made in the first dropdown, all options in the second dropdown are replaced with new ones. For example, let's say the first dropdown has thes ...

Cannot chain promises using 'then'

Having trouble understanding why the 'describeDir' promise chain is not working properly. Can anyone help me figure out what I did wrong here? Everything in the code seems to run, but functions like then or finally from the promise API never get ...

"Returning undefined: The outcome of using jQuery's .html() method on

I am having an issue with the JavaScript function I have created to load content from another URL into the current document. For some reason, both contentHtml and menuHtml variables are showing as undefined. Can someone please help me identify where I we ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

Retrieve the object filtered by a specific group from an array of data

I have a data object that contains various groups and rules within each group item. My task is to filter the rules based on a search query, while also displaying the group name associated with the filtered rule. { "id": "rulesCompany", "group": [ ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

Using Vue Router's `push()` method within an asynchronous function will solely modify the URL address

I created a custom loading component that displays while the route is being changed. To ensure the loading component properly waits for a second, the method needs to be asynchronous. However, since implementing this feature, I noticed that the router.push ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...

Show or hide the legend on a highchart dynamically

I am currently utilizing highchart in my application and I am interested in learning how to toggle the visibility of the legend within the highchart. Here is what I have attempted: var options = { chart: { type: 'column&a ...

The ASP.NET MVC controller did not receive the JSON object properly due to some missing properties

I am facing an issue when trying to pass a JSON object to my ASP.NET MVC controller. The JSON is set in JavaScript in this way: jsonChildren = '{ "childImproItems" : [{ "Theme":"tralalali" }, { "Theme":"tralalali" }]}'; ... $.ajax({ ...

Create a connection between a div and a React component, allowing for the seamless transfer of

I'm looking to implement a feature where clicking on a specific div will redirect the user to another page, similar to React Router. However, I currently lack the knowledge to make it happen. Below is the code snippet in question: const Card: React.FC ...

invoking a PHP function within a JavaScript script

In my collection of essential functions, there is one that I am particularly interested in: //the functions file //........ function user_exists($username){ $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') F ...

Displaying a division when a button is pressed

Despite my best efforts, I can't seem to get the chosen div to show and hide when the button is pressed. <button id="showButton" type="button">Show More</button> <div id="container"> <div id="fourthArticle"> <i ...