Utilizing Sequelize to establish associations between tables based on non-primary key columns

Here is the code snippet:

User.hasMany(UserMail, {foreignKey:'to_user_id', sourceKey:'id'});
User.hasMany(UserMail, {foreignKey:'from_user_id', sourceKey:'id'});

UserMail.belongsTo(User, {foreignKey: 'from_user_id'})
UserMail.belongsTo(User, {foreignKey: 'to_user_id'})

function getUserMail(req,res){
    // Authentication
    jwt.verify(req.headers.jwt, process.env.JWT_KEY,function(err,decoded) {
        if (err) {
            return res.status(401).send("Invalid token");
        }
        let id = decoded.id;

        return UserMail.findAll({
            where: {
                to_user_id: id,
                to_user_deleted: false
            },
            include:{
              model: User,

              on:{
                  id: Sequelize.where(Sequelize.col("User.id"), "=",Sequelize.col("UserMail.from_user_id"))
              },

                attributes:['username']
            },
            order:[['id', 'DESC']]
        }).then(mail=> {
            return res.status(200).send(mail);
        })

    })
}

Upon using this code, I encountered an error "Unhandled rejection SequelizeDatabaseError: missing FROM-clause entry for table "User"" but couldn't figure out what it means.

I attempted using

where:{
    id: UserMail.from_user_id;
}

However, every execution of this query resulted in "User"."id" = NULL, failing to return any results. Various attempts were made to prevent NULL values but none succeeded.

The goal is to add a single column, username from the Users table, based on the relationship between from_user_id in the UserMail table and the Users table. Despite sounding simple, achieving this seems challenging.

While joining tables based on primary keys is easy by using

include:{[User]}

This method links User primary key to UserMail primary key, whereas the requirement is to join them based on a non-primary key column in UserMail.

Answer №1

In your code, use targetKey instead of sourceKey

I found this snippet in my own project, so I hope it can be useful for you

Country.hasMany(Region, { foreignKey: 'countrycode' })
Region.belongsTo(Country, { foreignKey: 'countrycode', targetKey:'countrycode' })

Therefore, your code should look like this:

User.hasMany(UserMail, {foreignKey:'from_user_id'})
UserMail.belongsTo(User, {foreignKey: 'from_user_id', targetKey:'id'})

Answer №2

Combining the "targetKey" and "sourceKey" is the solution that worked best for me, illustrated below:

TableB.belongsTo(models.TableA, { foreignKey: 'someID', targetKey: 'notTableAID' } );

TableA.hasOne(TableB, {
  sourceKey: 'NonPrimaryKeyColumnOnTheSourceModel',
  foreignKey: 'matchingColumnOnTheTargetModel'
});

Answer №3

{sourceKey: 'id'}: The value from UserMail.id will now populate the foreign key column in User.

To select a different column, replace sourceKey with your desired column name.

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

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...

Submit a Post request with a file and JSON information included

I'm encountering an issue while trying to pass files with a JSON object. It seems like there might be an error in the controller where the 'consumes' and 'produces' declarations are possibly incorrect. I need assistance on how to a ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

Testing Angular 2: Ensuring Component Properly Calls Router with Accurate Arguments

I'm facing an issue with a child component that includes a button element with 'routerlink' attribute for navigation upon clicking. The button does not have a '(click)' handler, only the routerlink. Currently, I am writing a unit ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

Challenges with E-commerce Project's Wishlist Feature

Currently, I am working on a project where clicking on the 'fa-heart' icon should toggle between solid and regular states to add or remove an item from the wishlist. However, my attempts so far have resulted in all product icons changing together ...

Incorporating numerous query parameters in Angular version 14

I am currently working on developing a multi-item filter feature for my application and I am faced with the challenge of sending multiple query parameters in the API request to retrieve filtered items. My main concern is whether there is a more efficient ...

Tips for accurately defining the return type for querySelector(All) connections

I enjoy doing this particular task, ensuring the types are correct. const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null; const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>; While hovering over query ...

Tips for displaying an array and iterating through its children in Angular 7

I am currently working on extracting the parent and its children to an array in order to display them using ngFor. However, I am encountering an issue where the children are not being displayed during the ngFor. I have a service that retrieves data from a ...

Spring Boot app experiences issues with certain endpoints not functioning properly upon receiving requests from the Angular front end

My code includes the following endpoint: @PutMapping(path = "/like/{id}") public void likeQuestion(@PathVariable("id") String id, @Valid @NotNull @RequestBody Student student) { logger.info(id, student); questionService.likeQues ...

Having trouble accessing a downloaded image saved in local files from Amazon S3 using the AWS SDK in Node.js

I am currently using the node.js aws-sdk package to download files from s3 storage. However, when I download a jpeg image and save it as a local file, I am unable to view it. Is this the correct method for downloading jpeg images? public async downloadFi ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

Challenges arising from the utilization of aggregate functions

I am attempting to divide individual values by the sum of their column. For example: SELECT (column1 / SUM(column1)) FROM Table a This works well, but when I add another necessary piece of information... SELECT column2 ,(column1 / SUM(column1)) ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

hiding html elements by using the display property set to none instead of physically removing

I am currently utilizing an if-else statement to display different HTML structures. As a result, the entire HTML is being rendered twice. Is there a way we can utilize 'display: none' instead? I attempted to use it in th ...

Ionic - Managing Large Image Galleries with Efficient Memory Usage

I've developed an app with Ionic that incorporates the latest angular 4 and ionic 3 versions. Within the app, there is a scrollable list displaying numerous large images. The issue arose on IOS due to memory crashes caused by the accumulation of the ...

In need of secure HTML, received a dose of Style instead

I am currently developing a component that loads html content dynamically and validates the loaded styles to prevent any mixing of app styles with the dynamic template's styles. This is the structure of my HTML component: <div class="modal-header ...

Exploring the connections among Angular, Angular-CLI, Angular-seed, and Ionic

I'm currently tackling a project in Angular 2. I'm a bit puzzled about the relationship between CLI, Seed, and Ionic with Angular. Are they considered sub-frameworks of Angular? ...