Loopback reset the sort order to ASC - loopback

I am using loopback 3. This is the API call that I am doing to fetch the record in descending order.
const orderDetail = await Order.app.models.OrderDetail.findOne(
{
where: { orderid: orderId },
order: 'index DESC',
}
);
But loopback is discarding my sort order and using INDEX default. Below is the sql that I get setting DEBUG strings.
SELECT "id","index","timestamp", ............. FROM "public"."orderdetail" ORDER BY "index" ASC LIMIT 1 +4ms
There is no scope defined in model definition.

I remembered that I have had override the find method of model where it had set the defult order. I had done this earlier to prevent default sort (order by id) which was causing database performance issue.
const builtInFindMethod = OrderDetail.find;
OrderDetail.find = function findOrderDetails(filter, ...args) {
const processedFilter = { ...filter, order: 'index ASC' };
return builtInFindMethod.apply(this, [processedFilter, ...args]);
};

Just need to change the order object, try the below given code :
const orderDetail = await Order.app.models.OrderDetail.findOne(
{
where: { orderid: orderId },
order: ['index DESC'],
});

Related

Prisma: Finding items where two fields have the same value

I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})

Why is double underscore needed here for accessing table field?

I came across a GitHub issue about sorting rows with TypeORM. I found this comment did work for my problem.
Quote:
async sortWithRelations(entityRepository) {
// Assuming repository classname is RepoX
let repoOptions = {
relations: ['relationA', 'relationB'],
where: qb => {
// Filter if required
qb.where('RepoX__relationA.fieldY = :val', {val: 'searchedValue'});
// Then sort
qb.orderBy({
'RepoX__relationA.fieldYYY': 'DESC',
'RepoX__relationB.fieldZZZ': 'DESC'
// '{repositoryClassName}__{relationName}.fieldName
// [+ __{childRelations} for every child relations]
});
}
};
However, I have no idea why RepositoryClassName__ accompanied with double underscore is needed to access the table column?
'RelationName.FieldName': 'DESC' will result in error instead.

Objection.js alias to relationMapping

I have a working relation mapping with Objection / Knex / Sql server that is causing a problem when the results are paged.
components: {
relation: BaseModel.HasManyRelation,
modelClass: Component,
join: {
from: 'vehicle.id',
to: 'component.vehicleID'
}
}
When I use withGraphFetched to get related components for every vehicle, the query fails if I include the 'vehicle.id' in the original select.
static getFieldList() {
return [
'id',
'mark',
'model'
].
}
static getPagedList(page, pagelength) {
return this.query()
.select(this.getFieldList())
.withGraphFetched('components')
.page(page, pagelength)
}
Now, when paging is done, Objection / Knex runs a second query after the primary one to fetch the total number of rows. Objection adds 'vehicle.id' from the relation mapping to the query, thus causing the query to fail because the column 'id' is now fetched twice for the subquery.
exec sp_executesql #statement=N'select count(*) as [count] from (select [id], [mark], [model], [id] from [vehicle]) as [temp]'
My question is, how can this be avoided? Can I use some alias in the relation mapping? I tried 'vehicle.id as vehicleFK' in the relation mapping but that caused the withGraphFetched to not run at all.
there might be two ways to try to solve your issue
get rid of component's id column
const componentsSelectList = ()=>{
// select columns you need from components without the id column
return [
'column1', // columns you need
'column2'
]
}
static getPagedList(page, pagelength) {
return this.query()
.select(this.getFieldList())
.withGraphFetched('components',{minimize: true})
.modifyGraph('components',builder => builder.select(componentsSelectList()))
.page(page, pagelength)
}
use ref function from objection to reference the id column from which table
const {ref} = require('objection')
...
static getFieldList() {
return [
ref('vehicle.id'),
'mark',
'model'
].
}
static getPagedList(page, pagelength) {
return this.query()
.select(this.getFieldList())
.withGraphFetched('components')
.page(page, pagelength)
}
...

Sequelize bulk update with inner join

I am currently working with Sequelize and can not figure out how to update bulk when im associating two tables together. I have the follow:
Tables:
members
user_id
channel_id
all
activities
user_id
channel_id
I am trying to update members.all when the user_ids match, members.channel_id is 2 and activities.channel_id is not 2.
Here is working Postgresql:
UPDATE members AS m
SET "all" = true
FROM activities AS a
WHERE m.user_id = a.user_id
AND m.channel_id = 2
AND a.current_channel != 2;
Is this possible to do is sequelize? How do include a.current_channel != 2 into my current update?
Member.update(
{ all: true },
{ where: { channel_id: channelId } },
)
When I try to add an include it does not work.
I think you can't do something like that using Sequelize update method. I would use the include option in a findAll method, but as far as I can see on the documentation, there is no include option for the update method.
You could use a raw query to use directly the query.
sequelize.query("UPDATE members AS m SET "all" = true FROM activities AS a WHERE m.user_id = a.user_id AND m.channel_id = 2 AND a.current_channel != 2").spread((results, metadata) => {
// Results will be an empty array and metadata will contain the number of affected rows.
});
Generally, i use this hack
models.findAll({
where: {
// which models to update
}
}).then(targets => {
models.target.update({
// your updates
},{
where : {
target_primary_key: targets.map(t => t.primary_key)
}
})
})

pg-promise update where in custom array

How can the following postgresql query be written using the npm pg-promise package?
update schedule
set student_id = 'a1ef71bc6d02124977d4'
where teacher_id = '6b33092f503a3ddcc34' and (start_day_of_week, start_time) in (VALUES ('M', (cast('17:00:00' as time))), ('T', (cast('19:00:00' as time))));
I didn't see anything in the formatter namespace that can help accomplish this. https://vitaly-t.github.io/pg-promise/formatting.html
I cannot inject the 'cast' piece into the '17:00:00' value without it being considered part of the time string itself.
The first piece of the query is easy. It's the part after VALUES that i can't figure out.
First piece:
var query = `update schedule
set student_id = $1
where teacher_id = $2 and (start_day_of_week, start_time) in (VALUES $3)`;
var inserts = [studentId, teacherId, values];
I'm using this messiness right now for $3 (not working yet), but it completely bypasses all escaping/security built into pg-promise:
const buildPreparedParams = function(arr, colNames){
let newArr = [];
let rowNumber = 0
arr.forEach((row) => {
const rowVal = (rowNumber > 0 ? ', ' : '') +
`('${row.startDayOfWeek}', (cast('${row.startTime}' as time)))`;
newArr.push(rowVal);
});
return newArr;
};
The structure I am trying to convert into this sql query is:
[{
"startTime":"17:00:00",
"startDayOfWeek":"U"
},
{
"startTime":"16:00:00",
"startDayOfWeek":"T"
}]
Use CSV Filter for the last part: IN (VALUES $3:csv).
And to make each item in the array format itself correctly, apply Custom Type Formatting:
const data = [{
startTime: '17:00:00',
startDayOfWeek: 'U'
},
{
startTime: '16:00:00',
startDayOfWeek: 'T'
}];
const values = data.map(d => ({
toPostgres: () => pgp.as.format('(${startDayOfWeek},(cast(${startTime} as time))', d),
rawType: true
}));
Now passing in values for $3:csv will format your values correctly:
('U',(cast('17:00:00' as time)),('T',(cast('16:00:00' as time))