Unable to filter using lodash | nuxt - lodash

How can I filter using lodash, I use the response of an axios call to get the data
var wahahaha = _.filter(response.data.results, o => o.date >= this.$data.endofMonth && o.date <= this.$data.startofMonth);
console.log(wahahaha)
How can I query using the function

It seems like you have the date ranges swapped:
_.filter(response.data.results, o => o.date >= this.$data.startofMonth && o.date <= this.$data.endofMonth)
Should be less than end of month and bigger than start of the month no?

Related

<= less than equal to does't work as expected for sequilize query in nodejs

I have the following query in sequilize.js
const [results] = await sequelize.query(`select DISTINCT ON (variant_id) variant_id, Count(wl) as count, pds.name AS name,
CASE
WHEN pvs.name is NULL THEN pds.name
ELSE pvs.name
END
as variant_name,
im.url as img_url
from wish_lists as wl
LEFT JOIN products AS pds ON pds.id = wl.product_id
LEFT JOIN images as im on im.product_id = wl.product_id
LEFT JOIN product_variants as pvs ON pvs.id = wl.variant_id
where wl.created_at >= '${startDate}' AND wl.created_at <= '${endDate}' AND wl.tenant_id=${merchant_id}
group by ( variant_id, pds.name, im.url, pvs.name) LIMIT 100 OFFSET 0`)
The problem is if today is the 20th and i have products in the db that are selected on the 20th the query does't include those even though i have <= for the endDate, why is that ?
So why is the same day entries not being selected ?
Firstly, take a look at timezone of datetime data in database and in query param.
Secondly, created_at is the timestamp, which contain Time data (for example 2019-12-20T01:20:30.000Z). Then, your query param ${endDate} is just Date data only, it will append time = 0 (which is 00:00:00.000) before the comparison.
So the comparison would look like:
2019-12-20T01:20:30.000Z <= 2019-12-20T00:00:00.000Z
And the result is false, then it cannot be selected.

Convert SQL query to Linq (Need help to write sql query to linq)

This is my query returns me accurate result that I want. I want to write this in LINQ.
select i.reportdate,co.naam,i.issueid,i.vrijetekst,i.lockuser,te.teamnaam, count(ie.issueid) as events, sum(ie.bestedetijd) as Tijd
from company co,hoofdcontracten hc,subcontracten sc,sonderhoud so,g2issues i,g2issueevents ie, g2issuestatus iss,teams te,locatie l
Where co.companyid = hc.companyid And
hc.hcontractid = sc.hcontractid and
so.scontractid = sc.scontractid and
sc.scontractid = i.scontractid and
i.issueid = ie.issueid and
so.teamid = te.teamid and
ie.locatieid = l.locatieid and
l.bezoek = 0 and
i.issuestatusid = iss.issuestatusid and
fase < 7 and
co.companyid <> 165
group by i.reportdate,co.naam,i.issueid,i.vrijetekst,i.lockuser,te.teamnaam ,i.reportdate
having sum(ie.bestedetijd)>123
I am trying this but confused at select clause. How can I use aggregate function in select clause and group by clause also.
var myList = (from co in _context.Company
from hc in _context.Hoofdcontracten
from sc in _context.Subcontracten
from so in _context.Sonderhoud
from i in _context.G2issues
from ie in _context.G2issueEvents
from iss in _context.G2issueStatus
from te in _context.Teams
from l in _context.Locatie
where
co.CompanyId == hc.CompanyId
&& hc.HcontractId == sc.HcontractId
&& so.ScontractId == sc.ScontractId
&& sc.ScontractId == i.ScontractId
&& i.IssueId == ie.IssueId
&& so.Teamid == te.Teamid
&& ie.LocatieId == l.LocatieId
&& l.Bezoek == false
&& i.IssuestatusId == iss.IssueStatusId
&& iss.Fase < 7
&& co.CompanyId != 165
select new { }).ToList();
My! Someone was trying to save a few minutes typing time using all kinds of undecipherable variable names like hc, sc, so, i, ie, iss, without bothering that this would tenfold the time needed to understand what happens.
I haven't tried to decipher your query fully, apparently you thought it was not needed to show your entity framework classes and relation between them.
What I gather is that you want to perform a big join and then select several columns from the join. You want to group the resulting collection into groups of items that have the same reportdate, name, issueid, .... You want the bestede tijd on all items in each group, and you want the number of items in the group
LINQ has two types of syntaxes which in fact do the same: Query syntax and Method syntax. Although I can read the query syntax, I'm more familiar with the method syntax, so my answer will be using the method syntax. I guess you'll understand what happens.
I'll do it in smaller steps, you can concatenate all steps into one if you want.
First you do a big join, after which you select some columns. A big join is one of the few statements that are easier when written in query syntax (See SO: LINQ method syntax for multiple left join)
var bigJoin = from hc in _context.Hoofdcontracten
from sc in _context.Subcontracten
from so in _context.Sonderhoud
...
from l in _context.Locatie
where
co.CompanyId == hc.CompanyId
&& hc.HcontractId == sc.HcontractId
...
&& iss.Fase < 7
&& co.CompanyId != 165
select new
{
hc,
sc,
so,
... // etc select only items you'll use to create your end result
};
Now you've got a big table with the join results. You want to divide this table into groups with the same value for
{
i.reportdate,
co.naam,
i.issueid,
i.vrijetekst,
i.lockuser,
te.teamnaam,
}
(by the way: you mentioned reportdate twice in your GroupBy, I guess that's not what you meant)
This grouping is done using Enumerable.GroupBy.
var groups = bigjoin.GroupBy(joinedItem => new
{ // the items to group on: all elements in the group have the same values
ReportDate = i.Reportdate,
CompanyName = co.naam,
IssueId = i.issueid,
FreeText = i.vrijetekst,
LockUser = i.lockuser,
TeamName = te.teamnaam,
});
The result is a collection of groups. Each group contains the original bigJoin items that have the same value for for ReportDate, CompanyName, etc. This common value is in group.Key
Now from every group you want the following items:
Several of the common values in the group (ReportDate, CompanyName, IssueId, ...). We get them from the Key of the group
Tijd = the sum of ie.bestedeTijd of all elements in the group
Events = is the number of ie.IssueId of all elements in the group. As every element in the group has only one ie.IssueId, the result is also the number of elements in the group.
From this result, you only want to keep those with a Tijd > 123
So we'll do a new select on the groups, followed by a Where on Tijd
var result = groups.Select(group => new
{
Tijd = group.Sum(groupElement => groupElement.ie.bestedetijd),
Events = group.Count(),
// the other fields can be taken from the key
ReportDate = group.Key.reportdate,
CompanyName = group.Key.CompanyName,
IssueId = group.Key.Issueid,
FreeText = group.Key.FreeText,
LockUser = group.Key.LockUser,
TeamName = group.Key.TeamName,
})
.Where(resultItem => resultItem.Tijd > 123);

Convert SQL with multiple join into LINQ

I would like to know how can i change the following sql statement into Linq or Lambda Extension in C#
SELECT m.mdes as AgeGroup,COUNT(DISTINCT(mbcd))as "No.of Member" FROM mageg m
LEFT JOIN (select distinct(mbcd) ,mage
FROMtevtl
JOIN mvipm
ON tevtl.mbcd = mvipm.mvip
WHERE datm >= '2014-04-01'
AND datm <= '2014-04-30'
)vip
ON m.tage >= vip.mage AND m.fage <= vip.mage
GROUP BY m.mdes
I manage to do the first half of the LINQ statement. Not sure If it is correct
here is the first half. I do not know how to connect with the left join.
(from mem in mvipms
from log in tevtls
from grp in magegs
where mem.mage >=grp.fage && mem.mage <=grp.tage && mem.mvip.Equals(log.mbcd)
&& log.datm >= DateTime.Parse("2014-04-01") && log.datm <= DateTime.Parse("2014-04-30")
select new {mem.mvip,grp.mdes}).Distinct()
Pls advice. I am using the MSSQL 2008 and VS2010.
Thanks a million.
I am no expert on LINQ, but since no-one else has answered, here goes!
Firstly you cannot (AFAIK) do a LINQ join on anything other than equals so the structure of your LEFT JOIN has to change. Partly for debugging purposes, but also for readability, I prefer to layout my LINQ in bite-size chunks, so what I would do in your case is something like this (assuming I have understood your data structure correctly):
var vip = (from t in tevtl
join v in mvipl
on t.mbcd equals v.mvip
where t.datm >= new DateTime(2014, 4, 1) && t.datm <= new DateTime(2014, 4, 30)
select new { t.mbcd, v.mage }).Distinct();
var mv = from m in magegl
from v in vip
where m.tage >= v.mage && m.fage <= v.mage
select new
{
m.mdes,
v.mbcd
};
var gmv = from m in mv
group m by new { m.mdes } into grp
select new
{
mdes = grp.Key.mdes,
CountMBCD = grp.Count()
};
var lj = from m in magegl
join v in gmv
on m.mdes equals v.mdes into lhs
from x in lhs.DefaultIfEmpty()
select new
{
AgeGroup = m.mdes,
CountMBCD = x != null ? x.CountMBCD : 0
};
By way of explanation. mv is the equivalent structure for your left join in that it has the relevant where clause, but obviously it does not contain any nulls - it is equivalent to an INNER JOIN. gmv is a group on mv, so is still effectively an INNER JOIN. Then to pick up the missing mdes (if any) I re-join on magel with the added syntax DefaultIfEmpty() - this converts the join into the equivalent of a LEFT OUTER JOIN.
Without any sample data, I haven't been able to test this, but I hope it gives you enough to point you in the right direction!

Giving different record set after changing simple SQL query to LINQ query

I have write the below query in simple SQL,
I want to change it to use LINQ, I have tried, but my LINQ query and the original SQL statement are giving different record sets.
Simple SQL Query:
select *
from Paymentadvices
where status = 3
and Id in (select PaymentAdviceId from Approvals where ApprovedById = 13)
LINQ:
var myPaymentAdviceList = from pa in db.PaymentAdvices
where pa.Status == 3
join Ap in db.Approvals on pa.Id equals
Ap.PaymentAdviceId
where Ap.EmployeeId == 13
orderby pa.PaidDate descending
select pa;
I am not supposed to use join I guess, What should I use ?
var a = db.Approvals.Where( x => x.ApprovalById = 13).PaymentAdviceId;
var b = db.Paymentadvices.Where(x => x.status ==3 && a.Contains(x.Id);
.Contains() makes the WHERE IN () , you don't need a join there
var a = from a in db.Approvals
where a.ApprovedById == 3
select a.PaymentAdviceId;
var b = (from p in db.PaymentAdvices
where p.Status == 3 &&
a.Contains(p.Id)
select p).ToList();
those are both linq , the top is just lambda expressions which are commonly used in Linq queries. I would reccommend that you get used to reading/ writing both styles . The majority of code you'll come across in lambda style
I believe something like the below would work:
var query = from p in db.PaymentAdvices
where p.Status == 3 && db.Approvals
.Select(a => a.Id)
.Where(a => a.ApprovedById == 13)
.Contains(p.Id)
select p;
Though it's worth noting that #Scott Selby and #axrwkr solutions above are essentially the exact same thing in another form.

LINQ translation doesn't give the same results as my SQL query

Hi guys I have this SQL query (MSSQL), I'm doing a query where the result of joins are giving me the "top" row of newest row by date without having duplicates of results, you can find here information of what I'm doing http://goo.gl/Uv0FR The thing is this, I accomplished already the SQL query, Is Working as I'm expecting, I'm getting 1 row for each IDKEY uses in the clause "where pi.PlazaIe in ('','') without duplication
Select * from PlazaI pi
join (
Select * from PlazaE pe where
NOT EXISTS(SELECT 1 FROM PlazaE pe1
WHERE pe.Id_plaza = pe1.Id_plaza AND pe1.Fecha > pe.Fecha AND pe1.Fecha < GETDATE() and pe1.Id_Emp != 0)
) pe on pe.Id_plaza = pieepo.Id_plaza
join Emp e on pe.Id_Emp = e.Id_Emp
join View ct on ct.Id_Nodo = pe.id_nodo
where pi.PlazaIe in ('value1','value2')
The PROBLEM is when I'm trying to convert from SQL to LINQ is just can't make to happened. (I'm new in this world of Linq)
the following is my linq query.
var q1 = (from pe in db.PlazaEmpleados
where !db.PlazaEmpleados.Any
(
pe1 => (pe1.Id_plaza.Equals(pe.Id_plaza) && pe1.Fecha > pe.Fecha && pe1.Id_Emp != 0 && pe1.Fecha > DateTime.Now)
) select pe);
var q2 = (from pi in db.Context
join pe in (q1) on pi.Id_plaza equals pe.Id_plaza
select new EmpVO
{
Id_Nodo = pe.id_nodo,
Id_plaza = pi.PlazaSome,
Num_Plaza = pi.Id_plaza,
});
When I run this linq2sql query I'm getting duplicate results instead of just 1 for each value. So the thing is, I would like to know if someone can convert in a good way the SQL query to LINQ Query or point me where is the error.
thanks in advance.
Your check for the Date is different:
LINQ:
pe1.Fecha > DateTime.Now
SQL:
pe1.Fecha < GETDATE()
Isnt your LINQ supposed to be:
pe1.Fecha < DateTime.Now
I didn't find answer which resolve my problem, so what I finally did is to use the
db.ExecuteQuery<ObjectVO>(sqlQuery);
I know this is not the best practice and also don't resolve the question why my sql query and my linq query don't get the same result set, but non of the previous answer did.
The other thing is my query grown in complexity (new business logic requirement) have to join 7 table and search for Max dates and movement is some of them, so now is more complicated to transform the query to a linq to sql.
Thanks for the support.
this part:
var q1 = from pe in db.PlazaEmpleados
where !db.PlazaEmpleados.Any
(pe1 =>
pe1.Id_plaza.Equals(pe.Id_plaza) &&
pe1.Fecha > pe.Fecha &&
pe1.Id_Emp != 0 &&
pe1.Fecha < DateTime.Now
)
select pe;
In SQL you first use PlazaI then PlazaE- in Linq you both times use PlazaEmpleados.
Put your SQL query to stored procedure an add it to context. Then just call:
var q = context.MyProcedure(new object[] {"value1","value2"});