TypeORM find/findOne options(to find lastest one entitiy)

Viewed 17958

Now I am using Typecript, Express.js, TypeORM

I want to use Repository.find(or Repository.findOne) to find the latest ONE entity among entities which fit conditions.

This is my Entity


import {
    Entity,
    CreateDateColumn,
    UpdateDateColumn,
    PrimaryGeneratedColumn,
    Column,
    BaseEntity,
    ManyToOne,
} from "typeorm";

import { User } from "./user";
import { Product } from "./product";


@Entity()
export class Transaction extends BaseEntity {
    @PrimaryGeneratedColumn('increment', { type: "int" })
    id: number;

    @Column()
    user_id: number;

    @Column()
    product_id: number;

    @Column({
        type: "enum",
        enum: PaymentMethod,
        default: PaymentMethod.EL
    })
    paymentMethod: PaymentMethod;

    @Column()
    paymentValue: number;

    @Column()
    totalValue: number;

    @CreateDateColumn({ type: 'timestamp' })
    createdAt: Date;

    @UpdateDateColumn({ type: 'timestamp' })
    updatedAt: Date;
}

and this is my code to find the latest(According to createdAt)

let alltransactions = await transactionRepository.find({ where: [ {user_id : ownership.user_id}, {PaymentMethod: ownership.paymentMethod}]});
            

I am trying to use find all transactions that match to the conditions and ordering them by (so I put the latest one on the first) and get the first entitiy...!!

How can I solve it?

1 Answers

So you want to return the last inserted row that matches your AND condition.

let alltransactions = await transactionRepository.findOne({
    where: [ {user_id : ownership.user_id}, {PaymentMethod: ownership.paymentMethod}],
    order: { id: 'DESC' }
});
Related