Exploring SQL Joins using TypeORM

Here is the current Entity structure:

entity/Ticket.ts

import {Entity, PrimaryColumn, Column, OneToMany, ManyToOne, OneToOne, JoinColumn} from "typeorm";
import { Gym } from "./Gym";
import { TicketInteraction } from "./TicketInteraction";
import { TicketType } from "./TicketType";
import { User } from "./User";

@Entity()
export class Ticket {

    @PrimaryColumn('uuid')
    id: string;

    @ManyToOne(type => Gym, gym => gym.tickets)
    gym: Gym;

    @ManyToOne(type => User, user => user.tickets)
    user: User;

    @ManyToOne(type => TicketType, type => type.tickets)
    type: TicketType;

    @OneToMany(type => TicketInteraction, interactions => interactions.ticket, {
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
    })
    interactions: TicketInteraction[];

    @Column()
    title: string;
}

entity/TicketInteraction.ts

import {Entity, PrimaryColumn, Column, ManyToOne} from "typeorm";
import { Ticket } from "./Ticket";
import { User } from "./User";

@Entity()
export class TicketInteraction {

    @PrimaryColumn('uuid')
    id: string;

    @ManyToOne(type => Ticket, ticket => ticket.interacoes, {
        cascade: true
    })
    ticket: Ticket;

    @ManyToOne(type => User, user => user.interactions)
    user: User;

    @Column({ type: 'text' })
    description: string;

    @Column({ type: 'date' })
    date: string;

    @Column({ type: 'time' })
    time: string;
}

entity/User.ts

import {Entity, PrimaryColumn, Column, OneToMany, ManyToMany, ManyToOne} from "typeorm";
import { Gym } from "./Academia";
import { Ticket } from "./Ticket";
import { TicketInteracao } from "./TicketInteracao";
import { UserType } from "./UserType";

@Entity()
export class Usuario {

    @PrimaryColumn('uuid')
    id: string;

    @Column({ length: 50 })
    name: string;

    @ManyToOne(type => Gym, gym => gym.users, {
        cascade: true
    })
    gym: Gym;

    @ManyToOne(type => UserType, type => type.users, {
        cascade: true
    })
    type: UserType;

    @OneToMany(type => Ticket, tickets => tickets.user)
    tickets: Ticket[];

    @OneToMany(type => TicketInteraction, interactions => interactions.user)
    interactions: TicketInteraction[];
}

entity/UserType.ts

import {Entity, PrimaryColumn, Column, OneToMany} from "typeorm";
import { User } from "./User";

@Entity()
export class UserType {

    @PrimaryColumn('uuid')
    id: string;

    @Column({ length: 50 })
    description: string;

    @OneToMany(type => User, user => user.type, {
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
    })
    user: User[];
}

In summary, each user has many tickets and each ticket has many interactions with users who created them. To retrieve all the tickets of a user, along with the last interaction made on each ticket by a user with their respective type, I am struggling to construct the query. Here is my current attempt:

   let query = createQueryBuilder(Ticket, 'ticket')
      .leftJoinAndSelect('ticket.interacoes', 'ticket_interacao')
      .leftJoinAndSelect('ticket_interacao.usuario', 'usuario')
      .orderBy('ticket_interaction.date', 'DESC')
      .orderBy('ticket_interaction.time', 'DESC')

Here is the JSON output:

{
 [
   {
     "id": "0b8c5b62-1eb2-4b28-9fb9-97dc680a3c02",
     "title": "Title",
     "interactions": [
       {
         "id": "1e0bc060-ceb7-4722-898a-9bb22685afd0",
         "description": "Description",
         "date": "2021-03-07",
         "time": "18:45:52"
         "user": {
           "id": "0739f286-ecf5-4579-8efe-3062941a5e7f",
           "name": "usuario"
         }
       },
       {
         "id": "188bf283-8a0d-472f-83b9-2755d11016fe",
         "description": "Description",
         "date": "2021-03-07",
         "time": "18:44:21",
         "usuario": {
           "id": "a391dc7f-33af-4798-a41c-374a06f2f73e",
           "nome": "usuario"
         }
       }
     ]
   }
 ]
}

I am seeking assistance in constructing the complete query. Thank you!

Answer №1

In order to retrieve the most recent interaction associated with a ticket, you will need to perform a subquery joining the tables ticket and ticket_interactions.

Here is an example of how you can achieve this:

createQueryBuilder('ticket')
.leftJoin(`(SELECT id FROM ticket_interactions ORDER BY createdAt DESC LIMIT 1)`, 'latestInteraction', 'ticket.id = latestInteraction.id')
.leftJoin('users', 'u', 'u.id = ticket_interactions.user_id')
.select('ticket.id', 'id')
.addSelect('latestTicketInteraction.id', 'latestInteractionId')
.getRawOne()

Make sure to replace the table names and column names with those that match your database structure, and include any additional attributes in the SELECT statement as needed.

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

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...

Tips for demonstrating that two requests yield the same tab

I have a task involving PostgreSQL where I need to extract information about brands and the number of cars in my fleet. Query 1: Retrieve the list of brands along with the count of cars for each brand SELECT brand.name, COUNT(i) FROM brand GROUP BY brand ...

Experiencing difficulties with the node.save functionality when trying to integrate Drupal with Appcelerator Titanium

I am currently developing my first mobile app using Appcelerator Titanium, and I've encountered a problem that I can't seem to resolve. All other services are functioning properly through the JSON server (such as node.get, view.get, system.connec ...

Is there a way to transfer Rundeck variables into a JSON file?

During the job execution, I have a JSON file containing key pairs and I need to access the values from Rundeck Options dynamically. In shell script, we can use $RD_OPTIONS_<>. Is there a similar format that I can utilize in a JSON file to achieve thi ...

Storing a dictionary in MySQL using JSON format

I am looking to store a complex NSDictionary structure in a MySQL database. This structure includes nested arrays and dictionaries, making the data retrieval process a bit complex. The main dictionary contains: - NSString with key "note" - NSArray with ke ...

Exploring Out Parameters in MySQL

I am encountering an issue while trying to insert code into two separate tables... DELIMITER // create procedure usp_ItemView( p_itemname varchar(50), p_company varchar(50), p_model varchar(50), p_unit varchar(50), p_photo varchar(5 ...

Using node.js to integrate Microsoft bots with Teams may encounter issues when attempting to update the same activity due to a missing activity ID

Regarding my code, I have a basic card carousel with action buttons as shown below: actions = [ { "type": "Action.Submit", "title": "Qualify", "data": { "action" : "qualify_lead" } }, { ...

Parsing JSON response using JsonConverter in VBA

Trying to send a request API to Statistics Canada and struggling with a complex response string that I can't seem to extract any value from. I've attempted various syntax options in an effort to retrieve the "cansimId" without success. My aim i ...

Tips for enabling JSON access to the content inside a textarea element in HTML:

I'm attempting to develop a button that enables users to save edits to a post they write in a textarea using JSON. However, when attempting to save the data with a PUT request, I encounter the following error: raise JSONDecodeError("Expecting val ...

Having difficulty with removing items from a JSON array? Learn the ins and outs of unsetting,

Here's what I'm currently attempting: unset($jsonArr-[$json]); However, I keep encountering this error: Parse error: syntax error, unexpected '-', expecting ',' or ')' I believe solving this issue should be straig ...

What encoding does Algolia utilize to determine the size of a JSON entry - ASCII or UTF-8?

The FAQ document from Algolia states that the maximum size of an entry should be a minified JSON size of 10KB. However, it does not specify whether the JSON string should be ASCII or UTF-8 encoded, which makes it challenging to accurately calculate the siz ...

Get information from processed json list

I'm dealing with a code snippet where I need to extract each section of an array individually. Here is the code in question: $parsed = $parsed_json['forecast']['txt_forecast']['forecastday']; foreach($parsed as $key =& ...

The issue of returning a boolean value in an rxjs function leading to failure

Hey there, I am currently learning about rxjs and I want to create an observable that returns either true or false. This is my attempted code: checkLoggedIn(): Observable<boolean> { // Check with the server if the user is logged in if(this._tok ...

What is the process for transmitting a JSON object via POST in PHP?

I am trying to send a JSON object with a POST request in PHP. However, I have attempted various methods without success. Below is the code I have tried: function get_user_post_other_count($user_id, $call_for) { $params = array('user_id' =&g ...

Typescript: Displaying two values as input (one being disregarded)

Is there a way to display both the name and id values in an input box that is set to readonly? <input readonly type="text" [value]="car.name"> I need to also show the car id. Any suggestions on how to achieve this? ...

How to add a conditional AND clause in SQL Server?

I need to add an AND condition to my WHERE clause based on a specific condition. The issue I am currently dealing with is outlined below: DECLARE @param1 INT, @param2 INT SET @param1 = 1 SET @param2 = 1 SELECT * FROM Table1 t1 INNER JOIN Table2 t2 O ...

Exploring the World of TypeScript Decorators

I'm having trouble getting my custom @enumerable decorator to work properly. I followed the example in the documentation, but it's not functioning as expected. Am I overlooking something? Decorator export function enumerable(value: boolean) { ...

The implementation of a generic function interface in Typescript can pose a challenge

I've been working on incorporating a generic function interface, but I'm facing some challenges in getting it to function properly. IToken.ts export interface IToken { token: string; expires: number; } ITokenMapper.ts export interface ...

Calculating the average transaction value using SQL

I have a query about calculating the average quantity in transactions. Let's say I have 5 transactions, each with multiple items and their own quantity values. I need to find the average quantity per transaction. In my database design, I have two sepa ...

`How to cleverly fake dependencies with symbols in Jest, Vue3, and Typescript?`

I am faced with the following scenario: // symbols.ts - Injection Key defined as a Symbol export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService'); // main.ts - globally provides a service using the injection key app.provi ...