Apply v-for filter to the output of a MySQL join statement

Currently in the process of developing a project using Nuxt.js along with an express API and mysql database. Specifically, I am working on implementing comments functionality for a blog within the project. Each blog post can have multiple comments with potential replies to each comment. The data is stored in two separate tables named 'comments' and 'replies', where the 'replies' table has a foreign key relationship with the 'comments' table. To retrieve relevant information from the database, I utilize a JOIN query as follows:

SELECT * FROM comments LEFT JOIN replies ON comments.id = replies.comment_id;

This query returns a dataset structured like the following example:

+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
| id | post_id | user_id | content                       | created_at          | id | comment_id | reply_user_id | reply_content | reply_created_at    |
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
|  1 |       1 |       1 | Well thats a very lovely post | 2018-11-24 19:29:05 |  1 |          1 |             2 | it is indeed  | 2018-11-25 15:11:20 |
|  1 |       1 |       1 | Well thats a very lovely post | 2018-11-24 19:29:05 |  2 |          1 |             1 | why thanks    | 2018-11-25 15:11:39 |
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+

Now that I have successfully retrieved the necessary data, my goal is to present it efficiently. My initial attempt involves using 'v-for' to iterate through the data while avoiding duplication of the 'content' field. For instance:

<div v-for="comment in comments" :key="comment.reply_content">
  <p>{{comment.content}}</p>
  <p>{{comment.reply_content}}</p>
</div>

However, this approach results in displaying the same 'content' for each corresponding reply. To resolve this issue and display unique 'content' values alongside all relevant replies, I explored various JavaScript functions such as '.map()' and '.join()', but to no avail.

Although I resorted to executing two queries to achieve the desired outcome, I firmly believe there exists a more efficient solution utilizing the existing query structure.

Answer №1

To organize your comments, consider using a computed property along with the array method reduce. This code snippet demonstrates how you can achieve this:

computed: {
  organizedComments() {
    return this.comments.reduce((accumulator, current) => {
      const lastComment = accumulator[accumulator.length - 1];
      if (accumulator.length === 0 || current.text !== lastComment[lastComment.length - 1].text) {
        accumulator.push([]);
      }
      accumulator[accumulator.length - 1].push(current);
      return accumulator;
    }, []);
  }
}

You can then loop through the organized comments like so:

<div v-for="(commentGroup, index) in organizedComments" :key="index">
  <p>{{ commentGroup[0].text }}</p>
  <p v-for="reply in commentGroup" :key="reply.reply_text">{{ reply.reply_text }}</p>
</div>

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

Tips on modifying a particular item within a sub-document array using Mongoose?

Working on my node.js and mongoose project, I have a main Schema and a sub-Schema set up. const childrenSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, hobbies: [String] }) const parentSchema = new mongoose.Schema({ ...

Sending a result back to a Silverlight user control from a slightly intricate JavaScript function

I am working on a Silverlight user control that contains a textbox and a button. Within this Silverlight page, there can be multiple instances of these user controls. My goal is to have a JavaScript function trigger when the button is clicked. This functi ...

Tips for adding a dynamic variable into a react JSX map function

I have a component that receives a props with the value of either 'A', 'B', or 'C' based on the selection made in the parent element. The challenge is to use this props to dynamically select an option list locally, instead of ...

AngularJS Implementation for a Dynamic User Interface

After working with MS MVC and KendoUI controls for my web apps, I am now transitioning to a project that will utilize MS WebApi 2.0 for a restful pattern and a Responsive UI consisting of HTML5, Bootstrap, and AngularJS. While I have experience in writing ...

There was an error in Three.js: "Uncaught ReferenceError: THREE is not defined"

Every time I try to execute my javascript code, I encounter the error message "Uncaught ReferenceError: THREE is not defined". The problematic line in my code is: var renderer = new THREE.WebGLRenderer(); // I have included the three.js library in the ...

Having Trouble with Google Script App: Unable to Successfully Send Ajax Requests to My Web Application - Why?

Apologies if this question has been asked before, but I am struggling to find a solution. I am in need of assistance with a Google Script Web App. I have created a simple Web App for testing purposes using Google Script App, but I am facing issues with se ...

Instructions for capturing multi-dimensional arrays using forms in Vue

I have a snippet of code that looks like this: <div class="form-item"> <label for="list-0"><?php _e('List 0', 'test'); ?></label> <input name="list[0]" type="text" id="list-0" value=""> </div> &l ...

Leveraging the import statement within lib.d.ts to enhance Intellisense functionality in Visual Studio Code

Looking to streamline my JavaScript project by utilizing custom global variables and harnessing the power of VSCode intellisense for auto completion. Here's what I'm aiming for: See example of auto completion for 'lol' After some sear ...

Trouble arises when displaying data using AngularJS in an HTML environment

I'm currently facing a challenge understanding where I went wrong in my code. My goal is to display the initial array values in the table data, but so far, I haven't had much success. Here is the HTML section of the code; <body ng-controller ...

Is it possible to back up numerous databases [MySQL] simultaneously?

Greetings, I am currently managing several databases that require daily backups. I am utilizing a cronjob to schedule a batch file for this purpose. Among my databases, there are 10 in total, with 3 of them experiencing significant growth. Here is the curr ...

Aligning a child div within a parent div by using absolute positioning for both

When creating my components dynamically using JS, I utilize position: absolute for both the parent and children elements to achieve the desired placement. But I've encountered an issue with centering a div within another div. Most solutions suggest m ...

Two-column layout with consistent height vertically, but varying heights on individual rows

By using JavaScript, I am able to ensure that two columns have equal height. The left column contains user input which can vary in length, causing some columns to have more content than others. My current issue is that there are multiple rows instead of ju ...

The Laravel 5.7 VueJS component is successfully mounted, however it is not visible in the devtools

After spending hours troubleshooting, I'm still scratching my head over this issue. My component is running a console log code that indicates the component was successfully mounted, but it's not showing up in the dev tools. I've double-check ...

What is the widely used term for the container that allows for panning by dragging with a mouse?

I am looking to design a container that extends beyond the width of the page, allowing users to pan by dragging through empty space between controls without zooming in or out. What is this type of container control typically referred to as? I am intereste ...

What is the proper way to update data in reactjs?

I previously had code that successfully updated interval data in the browser and locale without any issues. class Main extends Component { constructor(props) { super(props); this.state = {data: []} } componentWillMount() { fetch('fi ...

Is there a way to perform nested association counting in Sequelize?

Exploring ways to tally product reviews within nested associations using a specific query. const user = await User.findOne({ where: { id: req.query.user }, attributes: ["id", "name"], include: [ { model: Category, as: "interest ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Controller using the 'as' syntax fails to add new object to array

Lately, I've been experimenting with the Controller as syntax in Angular. However, I seem to be struggling to grasp its functionality. I am currently following a tutorial that utilizes $scope to bind the members of the controller function rather than ...

Displaying a multitude of files in a Google Cloud bucket

I am currently utilizing a Node.js script to retrieve the number of files stored in a bucket on Google Cloud Storage. Interestingly, when dealing with a bucket containing approximately 30K files, the script executes successfully within a few seconds. Howe ...

Tips for populating an input field with data from a database using the .append method

I have a button that generates a new input field along with a default field <div class="container1"> <button class="add_form_field">Add Title</button> <div class="form-group label-floating"> <input type="text" id="ti ...