i'm trying to return softremoved products from db using typeorm, this is code:
async getEndedSalesOfUser(user: User): Promise<Sales[]> {
return await getRepository(Sales)
.createQueryBuilder("sales")
.leftJoin("sales.merchant", "m")
.addSelect(["m.id"])
.where("sales.merchant_id = :id", {id: user.id})
.andWhere("sales.deleted_at != :deleted_at", {deleted_at: null})
.getMany()
}
but in the end, typeorm adds NOT NULL, can anybody tell how to do?
Use .withDeleted() to include non-softdeleted data from your db.
Related
Is there any way to update an entity and return the result of the operation USING entity repository and NOT query Builder?
const result = await this.shipmentRepository.createQueryBuilder('sh')
.update()
.set({ ...infoToUpdate })
.where('shipment_number = :shipmentNumber', { shipmentNumber })
.returning("*")
.execute()
return result.raw[0]
I'm using this ^, this works properly but I want to know if I can do it using this syntaxis
const result = await this.shipmentRepository.update({ shipment_number: shipmentNumber }, infoToUpdate)
TypeORM documentation doesnt say anything about it
Can you help me? Thank u a lot!
I am trying to do a query that with query builder works fine but when I try to do it with entity repository fails.
Anyone can tell me what I am doing wrong?
Query Builder query
const dispatchHeader2 = await this.dispatchHeaderRepository.createQueryBuilder('dh')
.innerJoinAndSelect('dh.driver', 'driver')
.innerJoinAndSelect('dh.vehicle', 'vehicle')
.innerJoinAndSelect('vehicle.transportCompany', 'vtc')
.innerJoinAndSelect('dh.order', 'o')
.where('dh.order_id IN(:...ordersId)', { ordersId })
.andWhere('o.local_origin = :selected_dc', { selected_dc })
.getMany()
Query with Entity Repository
const dispatchHeader = await this.dispatchHeaderRepository.find({
relations: ['driver', 'vehicle', 'vehicle.transportCompany', 'order'],
where: {
order_id: In(ordersId),
order: {local_origin:selected_dc }
}
})
Relation on BD
If i do the query without the
order: {local_origin:selected_dc }
works fine, if i Add that line all fails
Thanks for the help.
img from typeorm Docs
Answering Youba
Dont let me do that
And the query doesnt give me an error, just an empty result. But the query itself dont take any parameters
I am new here recently joined and New in Type ORM My code that I am trying
FIRST QUERY: I would like to use this approach but not sure how I can group by with count on the column and then order by desc on that column
const result = await this.jobViewsRepository.find({
relations: ["jobs"],
loadEagerRelations: true,
order: { id: "DESC" },
skip: offset,
take: limit,
}
);
I am trying if I can use this in my above query
SECOND QUERY: IT'S WORKING FOR ME PERFECTLY THE RESULT I AM LOOKING
const res = await this.jobViewsRepository.createQueryBuilder('jobViews')
.addSelect("COUNT(jobViews.user_id) AS jobViews_total_count" )
.leftJoinAndSelect(Jobs, "jobs", "jobs.id = jobViews.job_id")
.where("jobs.user_id != :id", { id: user_id })
.groupBy("jobViews.job_id")**
.orderBy('jobViews_total_count', 'DESC')**
.limit(limit)
.offset(offset)
.getRawMany();
Please if any can help me out in this will be really appreciated
Thanks
At least in the current version there is no way to do this feature (neither in the documentation nor in the web)
I believe you can use .query to write your own query
Now is the only one way is to use queryBuilder And .groupBy("user.id") with .addGroupBy("user.id")
https://orkhan.gitbook.io/typeorm/docs/select-query-builder#adding-group-by-expression
Or write raw query:
import { getManager } from 'typeorm';
const entityManager = getManager();
const someQuery = await entityManager.query(`
SELECT
fw."X",
fw."Y",
ew.*
FROM "table1" as fw
JOIN "table2" as ew
ON fw."X" = $1 AND ew.id = fw."Y";
`, [param1]);
you use findAndCount to count the result size
result = await this.jobViewsRepository.findAndCount({ ... })
the result = [data,count]
I have a mutation createPet and want it to throw an error if the user already has 5 pets created.
I was thinking that something like this will work but it doesn't:
const petsCount = await db.pets({
where: { owner: user.id },
}).count();
I also didn't find anything in the docs
To retrieve a count, you can use Aggregations:
const petsCount = await prisma
.petsConnection({where: {owner: user.id}})
.aggregate()
.count()
Source: documentation
I have the following code in my chat application based on NodeJS and MongoDB to change admin for room:
export function setAdmin(room, user) {
const userGuid = getGuid(user);
if (room.users && room.users.length) {
// filter current and new
room.users = room.users.filter(guid =>
guid !== room.adminGuid && guid !== userGuid
);
} else {
room.users = [];
}
room.users.push(userGuid);
room.adminGuid = userGuid;
return roomsCollection.save(room, { w: 1 });
}
Each room have only 2 users: admin and customer.
To update several rooms:
const rooms = await roomsCollection.find({ adminGuid: currentAdminGuid }).toArray();
for (const room of rooms) {
await setAdmin(room, newAdminUser);
}
I had some problems under highload with my application. They were resolved with help of indexes.
But after, working with MongoDB dump I found out that I have rooms with 3 users guids in room.users array. I think that save works as update for exist document, but how it updates array? If $set, why I have such 3 users rooms. Any thoughts how it would be possible?
save() behaves as insert if document does not exist. You have to use update() with {upsert: false}
some resources to update array: Array Query, array Operator
simple tutorial to nest array inside document, here
advanced example of dealing with multiple nested array, here