What is the process of linking a field in a separate table within an Angular datatable using a foreign key?

I am facing a challenge in Angular with a data table where one of the fields is a foreign key (computer_id). Instead of displaying this ID, I want to show a field from another table. Specifically, I have a team ID as a foreign key in the records table that I am currently displaying, and I would like to display the name of that team which is a column in the equipment table (of which the team ID is a foreign key).

I'm struggling to figure out how to achieve this in angular, any suggestions or ideas would be greatly appreciated.

For fetching data from the database, I am using HTTP queries to consume the API with Django Rest Framework. My main concern is how to establish the relationship between the two tables once I retrieve the data through HTTP GET requests.

My database management system is MYSQL.

Below are snippets of the files that link the data to my data table:

service.ts

  public getAllEquipos(): Observable<Equipos[]> {
          return this.http.get<Equipos[]>(this.baseurl + 'equipos');
          } 

  public getAllPort(): Observable<Port[]> {
          return this.http.get<Port[]>(this.baseurl + 'puertos');
          } 

home.component.ts

export class HomeComponent implements OnInit {

  nuevosEquipos: any[]=[];
    constructor(
      // Inject services
      private http: HttpRequestsService,
      private service:PrtgService,
      private dialog: MatDialog,

    ) { }

    displayedColumns: string[] = ['id_equipo', 'nombre', 'vendedor','ip_gestion','tipo','localidad','categoria','name_port','ultima_actualizacion','actions',];  
    dataSource:any;  

@ViewChild(). 
    @ViewChild(MatPaginator) paginator: MatPaginator;
    //@ViewChild(MatSort) sort: MatSort;                    

    ngOnInit() {                        

      this.service.getAllEquipos().subscribe(Data => { 
        console.log(Data);
      })

    this.RenderDataTable()  

    }

    RenderDataTable() {   

      this.service.getAllEquipos().subscribe(  
        (res) => {  
          this.dataSource = new MatTableDataSource();  
          this.dataSource.data = res;  
          this.dataSource.paginator = this.paginator;
           console.log(res)

        },  
        (error) => {  
          console.log('An error occurred while trying to retrieve users!' + error);  
        });

    }

equipo.ts (Interface)

export interface Equipos { 

    id_equipo: number;
    nombre: string;
    vendedor: string;
    ip_gestion:string;
    tipo: string;
    localidad:string;
    categoria:string;
    id_port: number;
    ultima_actualizacion:string;
}

port.ts (Interface)

export interface Port { 

    id_port: number;
    name_port: string;
    }

home.component.html

 <mat-form-field>
    <input matInput (keyup)="DoFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>

  <fa-icon id='new_equi' [icon]=icon_new class="btn btn-primary" (click)="onCreate()" matTooltip="Create" matTooltipPosition="above"></fa-icon>
  <br>     
<div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource" align="center">

        <!-- Position Column -->
        <ng-container matColumnDef="id_equipo">
          <th mat-header-cell *matHeaderCellDef>Equipment ID</th>
          <td mat-cell *matCellDef="let element">{{element.id_equipo}}</td>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="nombre">
          <th mat-header-cell *matHeaderCellDef>Equipment Name</th>
          <td mat-cell *matCellDef="let element" >{{element.nombre}}</td>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="vendedor">
          <th mat-header-cell *matHeaderCellDef>Vendor</th>
          <td mat-cell *matCellDef="let element">{{element.vendedor}}</td>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="ip_gestion">
          <th mat-header-cell *matHeaderCellDef>Management IP</th>
          <td mat-cell *matCellDef="let element">{{element.ip_gestion}}</td>
        </ng-container>

        <ng-container matColumnDef="tipo">
          <th mat-header-cell *matHeaderCellDef>Type</th>
          <td mat-cell *matCellDef="let element">{{element.tipo}} </td>
        </ng-container>

        <ng-container matColumnDef="localidad">
          <th mat-header-cell *matHeaderCellDef>Location</th>
          <td mat-cell *matCellDef="let element">{{element.localidad}}</td>
        </ng-container>


        <ng-container matColumnDef="categoria">
          <th mat-header-cell *matHeaderCellDef>Category</th>
          <td mat-cell *matCellDef="let element">{{element.categoria}}</td>
        </ng-container>

        <ng-container matColumnDef="id_port_port">
          <th mat-header-cell *matHeaderCellDef>Port Name</th>
          <td mat-cell *matCellDef="let element">{{element.id_port}}</td>
        </ng-container>

        <ng-container matColumnDef="ultima_actualizacion">
          <th mat-header-cell *matHeaderCellDef>Last Update </th>
          <td mat-cell *matCellDef="let element">{{element.ultima_actualizacion | date:'d/M/yyyy, h:mm a'}}</td>
        </ng-container>

        <ng-container matColumnDef="actions">
          <th mat-header-cell *matHeaderCellDef>Actions</th>
          <td mat-cell *matCellDef="let element">
           <fa-icon [icon]=icon_edit class="btn btn-success" (click)=onEdit(element) matTooltip="Edit" matTooltipPosition="left"></fa-icon>&nbsp;
           <fa-icon [icon]=icon_delete class="btn btn-danger" matTooltip="Delete" matTooltipPosition="right" ></fa-icon>
          </td>
        </ng-container>

  </table>        
        <mat-paginator [pageSizeOptions]="[5,10,20,50,100]" showFirstLastButtons></mat-paginator>          
</div>

How can I display the name_port instead of the id_port attribute using the foreign key association?

Answer №1

When working in both the backend and frontend (specifically an Angular app), it's important to have separate models for creating (POST) and retrieving data. For example, let's consider a person model:

interface PersonForCreation {
    id: number;
    name: string;
    computerId: number;
}

The above model is used for creation and updating purposes. However, we also need a different model for GET requests, like this:

interface Person {
    id: number;
    name: string;
    computer: Computer
}

interface Computer{
    id: number;
    name: string;
}

Alternatively, you can structure the Person model for retrieval in the backend before sending it to the client as follows:

interface Person {
    id: number;
    name: string;
    computerName: string;
}

This way, you can display the `computerName` field in a data table or with `p.Computer.name`.

If you are retrieving ports and equipment separately without joining them at the backend, you can handle it in Angular using the following approach:

<ng-container matColumnDef="id_port_port">
      <th mat-header-cell *matHeaderCellDef>Port Name</th>
      <td mat-cell *matCellDef="let element">{getPortName(element.id_port)}}</td>
    </ng-container>

  public getPortName(portId) {
      // When requesting all ports with getAllport, save them in an array, dictionary, or regular array 
      // Then later find the port based on its ID and return its name
      return ports[portId];
  } 

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

Running XAMPP in Windows Safe Mode is a simple process that can help ensure

My Windows won't start up, possibly due to a virus, and I can't launch xampp on it. The only way I can start up is in safe mode. How can I run xampp in safe mode? I urgently need to backup my databases. Is there a way to back up my databases ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

Using a custom user model and an overridden save() method with django-social-auth

Currently, I have integrated django-social-auth into my project and I am quite impressed by its simplicity. However, the issue I am facing is that I am using a custom user model with an overridden save() method to set a default computed value for a speci ...

HyperlinkedRelatedField does not function as expected when used in conjunction with to_internal_value in Django Rest Framework

I've set up a HyperlinkedModelSerializer with references to other models using the HyperlinkedRelatedField and everything seems to be working smoothly: class LicenseSerializer(serializers.HyperlinkedModelSerializer): style = serializers.Hyperlink ...

Angular OpenID: Ensure user authentication before rendering application in web browser

Currently working with Angular 12 and utilizing angular-oauth2-oidc. Authentication has been set up successfully, but there is a brief moment where the application loads before redirecting to the login page. Is there a method to completely hide the app u ...

Error encountered with TypeScript when using Object.fromEntries to process fetched information

In my requests object, I have URLs assigned to names. I've attempted to fetch each URL and return the data with their corresponding names. Code async function fetchMovies(url: string) { const data = await fetch(baseURL + url).then((r) => r.j ...

Choose a form field by narrowing down the options based on the specific queryset within the model

I am having trouble populating a drop-down with the results of a queryset for my coach_id field in a form. I only want users to be able to select one option, not multiple. I am attempting to use a ModelMultipleChoiceField but without success... class Pers ...

Unable to populate TinyMCE editor in textarea through Ajax requests

I've been trying to figure this out for nearly 4 hours with no success. My form consists of a textarea and a drop-down list. The drop-down list is populated from a MySQL database. When I select an item from the drop-down, it should display the data i ...

Managing multiple databases in Django and dynamically switching between them

After exploring django, I am curious about a specific scenario. Despite reviewing the standard multiple database documentation, I have not found reference to this use case. If my understanding is incorrect, please correct me :) I envision having one prima ...

What steps do I need to take to configure the Django `Debugger` clock?

One way to activate the Django debugger is by using import pdb; pdb.set_trace(). At times, we forget to remove the debugger code before pushing it to the server. When a view containing the debugger is requested in such cases, the page may fail to load an ...

How to pass variables from the view function to the template using Django and Ajax?

I am faced with a challenge where I need to populate an element with data from two variables based on the user's selection from a list of choices. In order to achieve this, my view function retrieves the table id using post request and then fetches ad ...

Error encountered while executing SQL query - Retrieving data from table with specified criteria

I am currently faced with the challenge of creating a query that meets my specific requirements. The task involves selecting a modelid from the creature table where the id is 553, and then updating the column displayid in the creature_template table with t ...

What is the correct method for transmitting files via resteasy within an angular application?

I currently have a service implemented in an Angular 5 app: const httpOptions = { headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'multipart/form-data' }) }; @Injectable() export class Up ...

Angular: Issue with Pipe functionality

Recently, I've encountered an issue with a pipe that I created. Despite having what seems like clear and straightforward code, I can't seem to pinpoint the exact issue. Any thoughts or suggestions on what might be causing this problem? Here&apo ...

Issues with command functionality within the VS Code integrated terminal (Bash) causing disruptions

When using Visual Studio Code's integrated terminal with bash as the shell, I have noticed that commands like ng and tsc are not recognized. Can anyone shed some light on why this might be happening? ...

Show the MySQL data within a current div on a webpage with the help of

Seeking to extract and display the value from the first record's 'post' field, which is stored in a MySQL database using PHP.  The specific div where the value should be inserted is shown below: <div id="insert1"><?php echo($r ...

Validation messages in Angular only display once the form has been reset using the reset

I am having trouble with my form appearing clean without validation error messages after using the reset() function. Initially, my form looks clean as expected: https://i.sstatic.net/HLKPq.png However, if a user clicks the register button and encounters a ...

Upgrading to Python Django forms brings in the latest inputs

I've been working on setting up a registration form, but every time I test it, the new registrant overwrites the old registration. As a result, I can only have one user at a time. Any assistance would be greatly appreciated as I am unsure of what ste ...

Exploring alternative connections to access a user's profile

In my application, users can have either zero or one profile at a given time. However, I plan to introduce multiple profiles in the future. Accessing a user from "profileX" is straightforward: profile_x_object.user. But how can I establish a reverse relat ...

Searching for both the names of employees and their supervisors can be a challenge in MySQL when the table lacks a common numeric identifier such as Employee_id or employee number

If a table contains only two columns for employee names and their supervisors, without any other numeric columns like employee number or ID, how can the results be displayed? I am struggling to find a logical way to show the results. MySQL code to create ...