Typeorm querybuilder group by not working - typeorm

const purchaseStates = await this.purchaseState.createQueryBuilder('purchaseState')
.select('purchaseState.id')
.select('max(purchaseState.id)')
.addSelect('purchaseState.purchaseId')
.where('purchaseState.purchaseId IN (:...purchaseIds)', { purchaseIds })
.groupBy('purchaseState.purchaseId')
.getMany()
this creates query below
select
"purchaseState"."purchaseId" as "purchaseState_purchaseId",
"purchaseState"."id" as "purchaseState_id",
max("purchaseState"."id")
from
"purchase_state" "purchaseState"
where
"purchaseState"."purchaseId" in ($1,$2)
group by
"purchaseState"."purchaseId"
Why "purchaseState"."id" as "purchaseState_id" keep showing up?
I don't want to select "purchaseState"."id" but it keep show up in sql

Related

Typeorm createQueryBuilder.innnerJoinSelect() not returning the columns of a table

I'm attempting to select columns of two tables tradie,postcode_distance using innerJoinAndSelect but unfortunately, I'm not fetching those columns.
Here's what I'm trying with typeorm createQueryBuilder()
this.createQueryBuilder('tradie')
.innerJoin(
'tradie.categories',
'category',
'category.category_id = :categoryId',
{
categoryId,
},
)
.innerJoinAndSelect(
'postcode_distance',
'postcodeDistance',
'postcodeDistance.source = ANY(tradie.directoryPostcodes)',
)
.where('tradie.plan IN (:...planIds)', { planIds })
.andWhere('postcodeDistance.destination = :postcode', { postcode })
.andWhere('postcodeDistance.driving_distance <= :radius', { radius })
.andWhere('tradie.enable_spiral_search = TRUE')
.andWhere('tradie.is_active = TRUE')
.select('tradie')
Here's the SQL I'm expecting to be generated.
Select t.*,pd.*
FROM tradie t
INNER JOIN tradie_category tc
ON t.tradie_id=tc.tradie_id
INNER JOIN Category c ON
c.category_id=tc.category_id
AND c.category_id=$1
INNER JOIN postcode_distance pd ON
pd.source=ANY(t.directory_postcodes)
WHERE t.plan_id IN($2,$3)
AND pd.destination=$4 AND
pd.driving_distance<=$5 AND
t.enable_spiral_search=TRUE AND
t.is_active=TRUE
Seems like select() will reset the selected columns above it. Removing select() fixed it

How can I access "information_schema" with typeorm?

Trying to query information_schema with typeorm and it's failing, how can I access this data with typeorm?
QueryFailedError: relation " information_schema.columns" does not exist
const rawData = await connection.query(`
SELECT
   COLUMN_NAME
FROM
   information_schema.COLUMNS
WHERE
   TABLE_NAME = 'members';
`);
Had to modify the query:
const rawData = await connection.query(`
SELECT COLUMN_NAME
FROM "information_schema"."columns"
WHERE ("table_schema" = 'public' AND "table_name" = 'members')
`);
Found here https://wanago.io/2019/01/28/typeorm-migrations-postgres/

How to display the data of two tables in a view using LINQ lambda expression in ASP.Net MVC?

I'm having a hard time trying to display the data from two tables into a view using a linq lambda expression in ASP.net MVC.
I've tried this code:
var idSearchJoin = payoutdb.payout_transaction // your starting point - table in the "from" statement
.Join(payoutdb.payout_remittance, // the source table of the inner join
transaction => transaction.transid, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
remit => remit.transid, // Select the foreign key (the second part of the "on" clause)
(transaction, remit) => new { Transaction = transaction, Remit = remit }) // selection
.Where(transactremit => transactremit.Transaction.senderRefId == searchTxt).ToList();
I've joined the two tables but now my problem is that i can't put it into a view model to be able to display it to a view because the two tables have the same column transid so even if i created a new model to match the values of the result of linq expression it will not match because the transid cannot be initiated twice inside the same view model. Do you have any suggestions on how am i supposed to do this?
I am not sure what you mean by transid cannot be initiated twice. If you want to put your results set to your ViewModel, you need to put it right on your selection or after your query:
Instead of this:
(transaction, remit) => new { Transaction = transaction, Remit = remit }) // selection
Do this (MyViewModel is the name of my View Model):
(transaction, remit) => new MyViewModel()
{ field1 = transaction.transid, field2 = remit.whateverfield, field3 = transaction.whateverfield })
//selection, replace field1 with your correct fields
Then do the filtering (removed the Transaction word) :
.Where(transactremit => transactremit.senderRefId == searchTxt).ToList();

priority-web-sdk: fieldUpdate for choose field failed

My form contains a field with drop down values (the values came from the choose function) and when I am trying to update the field (with fieldUpdate) in the second time I always get the following error: "A record with the same value already exists in the screen", What is the correct order of actions that need to be done in order to achieve the right behaviour?
This is my attempt to achieve that:
await actions.loginTest();
const form = await actions.priority.formStart(this.formName,
this.onShowMessgeFunc, this.onUpdateFieldsFunc);
_formInstance = form;
const rows = await form.getRows(1);
console.log("parent form rows", rows);
await _formInstance.setActiveRow(1);
form.choose("CUSTNAME", '').then(options => {
let custOptions = options.SearchLine.map(x => {return {label:x.retval + " -
" + x.string1, value: x.retval }});
}).catch((err) => {
console.log("CHOOSE ERROR", err);
})
When I select a value from the drop-down, those are my actions:
await _formInstance.fieldUpdate("CUSTNAME", data.value);
await _formInstance.saveRow(1);
const rows = await _formInstance.getRows(1);
console.log("rows", rows);
In the first time it work's great, but when I select a different value for the second time I get an error that say that this value already exists (it's like it think that I am trying to update the value but I don't, I just want to get the values of other fields that return as a result of the field trigger when I leave the field in Priority). I don't have any purpose to change values, just getting information on other fields and data from sub-forms.
I don't have any purpose to change values, just getting information on other fields and data from sub-forms.
In order to achieve your purpose you could choose one of the following flows, that should work:
Recommended: Use getRows() after you have setSearchFilter() in order to retrieve the row you're interested in including its fields. Then easily setActiveRow() with its index to startSubForm(). You could always use clearRows() to clear the current rows and retrieve others.
Example:
const form = await actions.priority.formStart(this.formName,
this.onShowMessgeFunc, this.onUpdateFieldsFunc);
const filter = {
QueryValues:
[{
field: 'CUSTNAME',
fromval: value,
op: '='
}]
}
await form.setSearchFilter(filter)
const rows = await form.getRows(1);
console.log("parent form rows", rows);
await form.setActiveRow(1);
await form.startSubForm(1);
Perform the 'update' on a newRow() without calling getRows(). Then saveRow() and startSubForm() to get the information you need. Do this for each record you trying to retrieve its data.
Explanation: When calling getRows() you retrieve some rows. Then you cannot update a key field with a value that already exists in the retrieved rows otherwise you get that error.

Translating SQL statement with dates to Linq-to-Sql for use with EF4

I have the following SQL command:
SELECT CONVERT(varchar, Logged, 103) AS Visited, COUNT(ID) AS Totals
FROM tblStats
GROUP BY CONVERT(varchar, Logged, 103)
ORDER BY Visited DESC
I want to translate this into a L2S statement that can be used with the Entity Framework, but in working with datetime types, I'm getting various errors depending on how I try to attack the problem.
Approach:
var results = from s in db.Stats
group s by (s.Logged.Date.ToString()) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
Error:
LINQ to Entities does not recognize
the method 'System.String ToString()'
method, and this method cannot be
translated into a store expression.
Approach:
var results = from s in db.Stats
group s by (s.Logged.Date) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
Error:
The specified type member 'Date' is
not supported in LINQ to Entities.
Only initializers, entity members, and
entity navigation properties are
supported.
What syntax do I need to make the query work?
Try using the EntityFunctions.TruncateTime method:
var results = from s in db.Stats
group s by EntityFunctions.TruncateTime(s.Logged) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
Do you need the Date section in s.Logged.Date?
Have you tried this:
var results = from s in db.Stats
group s by (s.Logged) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
I'm assuming that Logged is the property (column in the table).
EDIT: you guys are way to quick.

Resources