How to search with each starting letter of words in sequelize - node.js

I want to get search results if my string is "customer details" .I am able to do a search if I type cust will get desired output but if I search using data keyword. I am getting no results. How to achieve with sequelize?
What I have tried -
sequelize.where(sequelize.fn('LOWER', sequelize.col('name')), 'LIKE', queryObj.keyword.toLowerCase() + '\%')
Generated Query
SELECT "Campaign"."id" FROM "Campaigns" AS "Campaign" LEFT OUTER JOIN "EmailCampaigns" AS "EmailCampaigns" ON "Campaign"."id" = "EmailCampaigns"."campaignId" AND ("EmailCampaigns"."deletedAt" IS NULL)
LEFT OUTER JOIN "CampaignEmailTemplates" AS "CampaignEmailTemplate" ON "Campaign"."id" = "CampaignEmailTemplate"."campaignId"
AND ("CampaignEmailTemplate"."deletedAt" IS NULL)
LEFT OUTER JOIN "CampaignScheduleRequests" AS "CampaignScheduleRequest" ON "Campaign"."id" = "CampaignScheduleRequest"."campaignId"
AND ("CampaignScheduleRequest"."deletedAt" IS NULL)
LEFT OUTER JOIN "CampaignStats" AS "CampaignStat" ON "Campaign"."id" = "CampaignStat"."campaignId" AND ("CampaignStat"."deletedAt" IS NULL)
WHERE ("Campaign"."deletedAt" IS NULL AND ("Campaign"."accountId" = 403
AND LOWER("Campaign"."name") iLIKE 'cust%')) ORDER BY "Campaign"."updatedAt" DESC;

sequelize.where(sequelize.fn('LOWER', sequelize.col('name')), {[Op.like]: `%${queryObj.keyword.toLowerCase()}%`}),

I found the way can be achieved by
sequelize.where(sequelize.fn('LOWER', sequelize.col('name')), {[Op.iRegexp]: `\\y${queryObj.keyword.toLowerCase()}.*\\y`})

Related

how to insert subQuery at join by "QueryDLS"

I'm using QueryDLS.
But I got some problems.
My Database server is MariaDB.
select s.* , a.user_id
from schedule s
left outer join(
select sch_idx, group_concat(user_id SEPARATOR ',') as user_id
from attendee a
group by sch_idx
) a
on s.idx = a.sch_idx;
and this is my code( Ofcoursly, It' is wrong)
public void selectJoin(){
JPAQueryFactory query = new JPAQueryFactory(em);
QSchedule qSchedule = QSchedule.schedule;
QAttendee qAttendee = QAttendee.attendee;
query.selectFrom(qSchedule)
.leftJoin(
query.select(
qAttendee.schIdx,
qAttendee.userId
).from(qAttendee)
.groupBy(qAttendee.schIdx)
).on(qSchedule.idx.eq(qAttendee.schIdx))
.fetch();
}
How can I insert subquery in the join like my sql sample?
And I Have to resolve Group_concat in QueryDSL
If I can not resolve my truoble by QueryDSL, Let me know what is best solutions.
please, I need your help!

TableAlias doesn't work with multiple joins

TableAlias isn't working with multiple joins.
The query:
var q = Db.From<Blog>(Db.TableAlias("b"))
.LeftJoin<Blog, BlogToBlogCategory>((b,btb)=> b.Id == btb.BlogId, Db.TableAlias("btbc"))
.Join<BlogToBlogCategory, BlogCategory>((bt,bc)=>bt.BlogCategoryId == bc.Id, Db.TableAlias("cats"))
.GroupBy(x => x.Id);
.Select("b.*, json_agg(cats) as BlogCategoriesJson");
var results = Db.Select<BlogQueryResponse>(q);
Generates this SQL:
SELECT b.*, json_agg(cats) as BlogCategoriesJson
FROM "blog" "b" LEFT JOIN "blog_to_blog_category" "btbc" ON ("b"."id" = "btbc"."blog_id") INNER JOIN "blog_category" "cats" ON ("blog_to_blog_category"."blog_category_id" = "cats"."id")
GROUP BY "b"."id"
This causes error because it is referencing "blog_to_blog_category" instead of btbc
The Db.TableAlias() only provides an alias for the target join table, your inner join does not specify the alias to use for the source table so it references the full table name as expected.
You can use Sql.TableAlias() in your LINQ Expression to reference a table alias, e.g:
var q = Db.From<Blog>(Db.TableAlias("b"))
.LeftJoin<Blog, BlogToBlogCategory>((b,btb)=> b.Id == btb.BlogId, Db.TableAlias("btbc"))
.Join<BlogToBlogCategory, BlogCategory>((bt,bc)=>
Sql.TableAlias(bt.BlogCategoryId, "btbc") == bc.Id, Db.TableAlias("cats"))
.GroupBy(x => x.Id);
.Select("b.*, json_agg(cats) as BlogCategoriesJson");

How to get one to many association in nested array when using Sequelize raw query

I am using following query
SELECT DISTINCT "branchManagement"."id",
"branchManagement"."branch_unique_id" AS "branchUniqueId",
"branchManagement"."name",
"branchManagement"."branch_head" AS "branchHead",
"branchManagement"."mobile_number" AS "mobileNumber",
"branchManagement"."email_id" AS "emailId",
"branchManagement"."address",
"branchManagement"."state_id" AS "stateId",
"branchManagement"."city_id" AS "cityId",
"branchManagement"."pin_code" AS "pinCode",
"branchManagement"."created_by" AS "createdBy",
"branchManagement"."modified_by" AS "modifiedBy",
"branchManagement"."is_active" AS "isActive",
"branchManagement"."createdAt",
"branchManagement"."updatedAt",
"state"."id" AS "state.id",
"state"."name" AS "state.name",
"city"."id" AS "city.id",
"city"."name" AS "city.name",
"assignedPincode"."id" AS "assignedPincode.id",
"assignedPincode"."branchManagementId" AS "assignedPincode.branchManagementId",
"assignedPincode"."pinCode" AS "assignedPincode.pinCode", "assignedPincode"."isActive" AS "assignedPincode.isActive",
"assignedPincode"."createdAt" AS "assignedPincode.createdAt", "assignedPincode"."updatedAt" AS "assignedPincode.updatedAt"
FROM "branch_management" AS "branchManagement"
LEFT OUTER JOIN "state" AS "state" ON "branchManagement"."state_id" = "state"."id"
LEFT OUTER JOIN "city" AS "city" ON "branchManagement"."city_id" = "city"."id"
LEFT OUTER JOIN "branchPincode" AS "assignedPincode" ON "branchManagement"."id" = "assignedPincode"."branchManagementId" AND "assignedPincode"."isActive" = true
WHERE (("branchManagement"."name" ILIKE '%' OR CAST("branchManagement"."id" AS VARCHAR) ILIKE '%' OR
"branchManagement"."branch_unique_id" ILIKE '%' OR "branchManagement"."branch_head" ILIKE '%' OR
CAST("mobile_number" AS VARCHAR) ILIKE '%'))
AND "branchManagement"."is_active" = true
expecting array of assignedPincode inside each branch but getting different record for each assignedPincode is there any way to use Sequelize eager loading in raw query
have tried raw:true and nest:true but getting expected output
If you need grouped associated model records you shouldn't use raw option because you will simply get a result similar to a result from sequelize.query.
If you simply don't need model instances you can convert them to plain objects (including nested associations) like this:
const models = await Model.findAll({})
const plainObjects = models.map(x => x.get({ plain: true })

JPQL LEFT JOIN is not working

I want to get the list of all Branch even if they have no accounts with user role
Query query = em.createQuery("SELECT NEW com.package.BranchInstructors(b,a) FROM Branch b LEFT JOIN b.accounts a WHERE b.dFlg = 0 AND a.userRole = :role ORDER BY b.name ASC");
query.setParameter("role", "user");
return query.getResultList();
Unfortunately it's returning only Branches with user role, it's like doing INNER JOIN instead.
Any idea what's going on?
just add the a.userRole is null condition to your query to avoid filtering the null userRole that you got from the left join
SELECT NEW com.package.BranchInstructors(b,a)
FROM Branch b
LEFT JOIN b.accounts a
WHERE b.dFlg = 0
AND (a.userRole = :role OR a.userRole IS NULL)
ORDER BY b.name ASC"
The problem is in your WHERE vs LEFT JOIN clause.
If you use LEFT JOIN table Accounts and use this table in the WHERE with AND condition, it behaves like a JOIN.
So, you can use WITH in the LEFT JOIN:
Query query = em.createQuery("SELECT NEW com.package.BranchInstructors(b,a) FROM Branch b
LEFT JOIN b.accounts a WITH a.userRole = :role
WHERE b.dFlg = 0 ORDER BY b.name ASC");

Converting a LEFT OUTER JOIN to Entity Framework

Here is a SQL Query I want to convert to EF4.3
command = database.GetSqlStringCommand(#"
select
H.AUTHENTICATION_ID,
USERNAME,
PERMISSIONS,
ORGANIZATION_IDENTIFIER,
O.ORGANIZATION_ID
from
AUTHENTICATION H
left join [AUTHORIZATION] T on H.AUTHENTICATION_ID=T.AUTHENTICATION_ID
join ORGANIZATION O on O.ORGANIZATION_ID = T.ORGANIZATION_ID
order by H.AUTHENTICATION_ID");
Here is the best LINQ I could come up with:
var query = from h in context.Authentications
join t in context.Authorizations on h.AuthenticationId equals t.Authentications.AuthenticationId
join o in context.Organizations on t.Organizations.OrganizationId equals o.OrganizationId
orderby
h.AuthenticationId
select new
{ AUTHENTICATION_ID = (Int16?)h.AuthenticationId,
h.Username,
t.Permissions,
o.OrganizationIdentifier,
OrganizationID = (Int16?)o.OrganizationId
};
I know i need to merge my first join (between Authorizations & Authentications) into, lets say x and apply DefaultIfEmpty but can't make out the syntax.
EDIT: Image for clarification:
Any help will be highly appreciated. Regards.
The basic syntax for a "left join" in Linq is like this:
from x in table1
join y in table2 on x.id equals y.id into jointable
from z in jointable.DefaultIfEmpty()
select new
{
x.Field1,
x.Field2,
x.Field3,
Field4 = z == null ? 0 : z.Field4
};
In your case, I'm a little confused because the entity relations you seem to be using in your Linq don't match the ones implied by your SQL; are the relationships here zero-or-one, zero-or-many, one-to-one, etc? Specifically, you're doing this:
from h in context.Authentications
join t in context.Authorizations on h.AuthenticationId equals t.Authentications.AuthenticationId
but your SQL implies that "Authentication" is the parent here with zero-or-more "Authorization" children, not the other way around, which would be more like:
from h in context.Authentications
from t in h.Authorizations.DefaultIfEmpty()
If you can give us a better idea of the data model and what data you expect to get out of it we can more easily explain how that query would look in Linq. Assuming that your relationships match what is implied by the SQL, you should be able to get what you want using the following Linq queries:
var query = from h in context.Authentications
from t in h.Authorizations.DefaultIfEmpty()
select new
{
h.AuthenticationId,
h.Username,
Permissions = t == null ? null : t.Permissions,
Organizations = t == null ? new EntitySet<Organization>() : t.Organizations
};
var query2 = from x in query
from o in x.organizations.DefaultIfEmpty()
select new
{
AUTHENTICATION_ID = (short?)x.AuthenticationId,
x.Username,
x.Permissions,
OrganizationIdentifier = o == null ? null : o.OrganizationIdentifier,
OrganizationID = o == null ? (short?)null : o.OrganizationID
};
Given the foreign keys that exist in the question diagram, how about something like this?
var query = from a in context.Authentications
select new
{
a.AuthenticationID,
a.Username,
a.Authorisations.Permissions ?? false,
a.Authorisations.Organisations.OrganisationIdentifier ?? 0
a.Authorisations.Organisations.OrganisationID ?? 0
};
I went ahead and moved the entire query to a Stored Procedure on the database. This solves the problem by avoiding LINQ and ObjectBuilder in the first place.

Resources