Search code examples
databasetypescripttypeorm

complex query in typeorm


hello every body i have entity that contain special property used for translation, when i try to get this special property usin typeorm i have this error: (node:3712) UnhandledPromiseRejectionWarning: QueryFailedError: syntax error at or near "[">>>

the entity is:

    import {
        Entity,
        PrimaryGeneratedColumn,
        Column, 
        BaseEntity, 
        OneToOne,
        JoinColumn,
        
        
      } from "typeorm";
      import {TextData} from "./TextData"
    
    @Entity()
    export class ContactUsDataNature extends BaseEntity {
    
    @PrimaryGeneratedColumn()
    id:number
    
    @OneToOne((type) => TextData, (text) => text.id, { cascade: true })
    @JoinColumn()
    dataNature:TextData
    
    }

the text data is:

    import { Entity, Column, PrimaryGeneratedColumn, BaseEntity } from "typeorm";
    
    @Entity()
    export class TextData extends BaseEntity{
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column({ type: "text", nullable: true })
        ar: string;
    
        @Column({ type: "text", nullable: true })
        en: string;
    
    }

i usually reach it like

    const contact=new ContactUSDataNature()
    console.log(contact.dataNature[en])

i tried the way to search but it doesn't work :

export const getContactDataNaturebyData = async (dataNature: string,language="en") =>{
  const container=await ContactUsDataNature.find({
    
    where: (qb) => {
        if (true) {
            qb.andWhere("ContactUsDataNature__dataNature.:lan = :parentId", {
              lan:"en",  
              parentId: 1,
            });
        }
       
    },
    order: { id: "DESC" },
    skip: 10,
    take: 0,
    });
    console.log(container)
    return container
    }

I need to get search in database for ContactUsDataNature if i get the final string value


Solution

  • You cannot parameterize the column names in a query.

    You can build the where by concatenating the column name:

    qb.andWhere("ContactUsDataNature__dataNature." + lan + " = :parentId", { parentId: 1 }); 
    

    When you test this, I recommend that you turn on TypeOrm full logging so you can see the actual generated SQL and you be able to quickly solve any problems. See TypeOrm logging.