Doctrine dql orderby with expression - doctrine

How can i do something like this in doctrine2 dql
Select m* from Members
WHERE MemberID = "6" or MemberId="3" or MemberID="5"
ORDER BY MemberID = "6" DESC, MemberId="3" DESC, MemberID="5" DESC;

Related

How to union two tables in the lef join of third table laravel?

I have these two queries:
SELECT salesconsultant AS emp_names,
lotid AS lot_id,
communityid AS lot_community,
lotnumber AS lot_no,
phasenumber AS lot_phase,
clientid AS lot_buyer,
lotstatusid AS lot_status,
lotaddress AS address,
pkg AS pack_id,
pkg_abbr AS pack_abbre,
deposit AS depst,
currentprice AS contract_price,
salesconsultant AS agent_name FROM `iv_reports_all_wms`
WHERE is_active_report = 0
AND lotid <> ''
AND rescined = 0 AND region IN ("SL")
ORDER BY `dig` ASC,
`agreedate` ASC
AND
(SELECT
id,
NAME,
lastname AS l_name
FROM
`iv_employee`
WHERE id = 6588)
UNION
(SELECT
userId AS id,
firstname AS NAME,
lastname AS l_name
FROM
`ivhusersdeleted`
WHERE userId = 6588)
I want to avoid to run the second query in foreach after the first query.
i want to use the second one in the left join of first in laravel. Can anyone help

How to use Union query with Laravel Eloquent?

This MySQL query Has union and Normalized I don't Know how to write laravel Query.
SELECT DISTINCT val
FROM
(
SELECT 'date' date_type, date val FROM user_presentation
 UNION
SELECT 'accept_date', accept_date FROM user_presentation
UNION
SELECT 'question_date', question_date FROM user_presentation
UNION
SELECT 'success_date', success_date FROM user_presentation
) normalized;
You may chain a series of unions in your Laravel code:
$first = DB::table('user_presentation')
->select('date');
$second = DB::table('user_presentation')
->select('accept_date');
$third = DB::table('user_presentation')
->select('question_date');
$fourth = DB::table('user_presentation')
->select('success_date AS val')
->union($first)
->union($second)
->union($third)
->get();
Note the above code actually corresponds to this query:
SELECT date AS val FROM user_presentation UNION
SELECT accept_date FROM user_presentation UNION
SELECT question_date FROM user_presentation UNION
SELECT success_date FROM user_presentation;
Also, the DISTINCT subquery you have should not be necessary, as the union query itself should remove all duplicate date values.
$userP = UserPresentation::get()
->only('date', 'accept_date', 'question_date', 'success_date')
->unique();
The 100% Laravel Way, using Collection, this one will select all four dates together, and Laravel Collection will find the unique rows from these selections.

Distinct on one column in linq with joins

I know we can get distinct on one column using following query:
I know we can get distinct on one column using following query:
SELECT *
FROM (SELECT A, B, C,
ROW_NUMBER() OVER (PARTITION BY B ORDER BY A) AS RowNumber
FROM MyTable
WHERE B LIKE 'FOO%') AS a
WHERE a.RowNumber = 1
I have used similar sql query in my case where i am joining multiple tables but my project is in mvc4 and i need linq to entity equivalent of the same. Here is my code:
select * from
(
select fp.URN_No,
ROW_NUMBER() OVER
(PARTITION BY pdh.ChangedOn ORDER BY fp.CreatedOn)
as num,
fp.CreatedOn, pdh.FarmersName, pdh.ChangedOn, cdh.Address1, cdh.State, ich.TypeOfCertificate, ich.IdentityNumber, bdh.bankType, bdh.bankName,
pidh.DistrictId, pidh.PacsRegistrationNumber, idh.IncomeLevel, idh.GrossAnnualIncome
from MST_FarmerProfile as fp inner join PersonalDetailsHistories as pdh on fp.personDetails_Id = pdh.PersonalDetails_Id
inner join ContactDetailsHistories as cdh on fp.contactDetails_Id = cdh.ContactDetails_Id
inner join IdentityCertificateHistories as ich on fp.IdentityCertificate_Id = ich.IdentityCertificate_Id
inner join BankDetailsHistories as bdh on fp.BankDetails_Id = bdh.BankDetails_Id
left join PacInsuranceDataHistories as pidh on fp.PacsInsuranceData_Id = pidh.PacsInsuranceData_Id
left join IncomeDetailsHistories as idh on fp.IncomeDetails_Id = idh.IncomeDetails_Id
where URN_No in(
select distinct MST_FarmerProfile_URN_No from PersonalDetailsHistories where MST_FarmerProfile_URN_No in(
select URN_No from MST_FarmerProfile where (CreatedOn>=#fromDate and CreatedOn<= #toDate and Status='Active')))
)a where a.num=1
Use this linq query after getting result from sql. p.ID is be your desire distinct column name
List<Person> distinctRecords = YourResultList
.GroupBy(p => new { p.ID})
.Select(g => g.First())
.ToList();

How to Group By Distinct in EF

I need to translate this SQL to Linq for use with Entity Framework:
SELECT TheDate, COUNT(DISTINCT IPAddress) as Count
FROM TheTable Group By TheDate
Order By TheDate
The difficulty is the Count(Distinct IPAddress).
Greg
from x in db.TheTable
group x by x.TheDate into g
orderby g.Key
select new
{
TheDate = g.Key,
DistinctIPCount = g.Select(x => x.IPAddress).Distinct().Count()
}

How to use GroupBy properly in LINQ?

I have 4 tables: Post, Category, Relation and Meta
A category can contains multiple posts, and the relation between them is stored in Relation table. A post then can has many extra info that are stored in Meta table. I want to list all post with categories and extra infos, then group them by post's ID.
I have the following query
select p.ID, p.Title, t.Name, m.Key, m.Value from Post p
left join Relation r on p.ID = r.Child
left join Category c on r.Parent = c.ID
left join Meta m on p.ID = m.Object
where m.Type = 'news'
order by p.ID
and with these sample data:
Post
ID Title
1 A
Category
ID Name
1 Tips
2 Tricks
Meta
ID Object Key Value
1 1 Key1 Value 1
2 1 Key2 Value 2
Relation
ID Child Parent
1 1 1
2 1 2
then the result will be
PostID Title Category Key Value
1 A Tips Key1 Value1
1 A Tips Key2 Value2
1 A Tricks Key1 Value1
1 A Tricks Key2 Value2
and I expected the result to be
PostID Title Categories Meta
1 A Tips, Tricks Key1=Value1, Key2=Value2
I wonder if we can convert the query from SQL to LINQ to Entities with EF v4 and the result is stored in a class like this
class Result
{
long ID,
string Title,
List<string> Categories,
Dictionary<string, string> Meta
}
Any helps would be appreciated.
What's the final result you expect from the query
I personally prefer to write the query like
var q = from r in Relation
join p in Post on r.Child equals p.ID
join t in Term on r.Parent equals t.ID
let x = new { p.ID, p.Title, t.Name }
group x by x.ID into g
select g;
this way I think (not sure) the sql generated will be simpler
Now that you're wanting to use EntityFramework, you would merely need to set up you database, edmx with a Result table with an ID and a Title, then Category and Meta tables. Then add one-to-many relationships from the Result table to each the Category and Meta tables.
I'm not 100% sure what you're trying to do, but obviously if you're grouping, the results have to be grouped by anything in the resultset, or be aggregated data. This query will retrieve your results and group by PostId, PostTitle, and CategoryName, generating a single SQL Statement:
var query = from p in Posts
from r in Relations
.Where(r => p.ID == r.Child)
.DefaultIfEmpty()
from c in Categories
.Where(c => r.Parent == c.ID)
.DefaultIfEmpty()
group p by new {ID = p.ID, Title = p.Title, Name = c.Name} into z
select new { ID = z.Key.ID, Title = z.Key.Title, Name = z.Key.Name };
Here is the SQL Generated by this statement:
SELECT [t3].[ID], [t3].[Title], [t3].[value] AS [Name]
FROM (
SELECT [t0].[ID], [t0].[Title], [t2].[Name] AS [value]
FROM [Post] AS [t0]
LEFT OUTER JOIN [Relation] AS [t1] ON [t0].[ID] = [t1].[Child]
LEFT OUTER JOIN [Category] AS [t2] ON [t1].[Parent] = [t2].[ID]
) AS [t3]
GROUP BY [t3].[ID], [t3].[Title], [t3].[value]
Here is the SQL Generated by your original statement:
SELECT [t0].[ID] AS [Key]
FROM [Post] AS [t0]
INNER JOIN [Relation] AS [t1] ON [t0].[ID] = [t1].[Child]
INNER JOIN [Category] AS [t2] ON [t1].[Parent] = [t2].[ID]
GROUP BY [t0].[ID]
GO
-- Region Parameters
DECLARE #x1 Int SET #x1 = 1
-- EndRegion
SELECT [t0].[ID], [t0].[Title], [t2].[Name]
FROM [Post] AS [t0]
INNER JOIN [Relation] AS [t1] ON [t0].[ID] = [t1].[Child]
INNER JOIN [Category] AS [t2] ON [t1].[Parent] = [t2].[ID]
WHERE ((#x1 IS NULL) AND ([t0].[ID] IS NULL)) OR ((#x1 IS NOT NULL) AND ([t0].[ID] IS NOT NULL) AND (#x1 = [t0].[ID]))
GO
-- Region Parameters
DECLARE #x1 Int SET #x1 = 2
-- EndRegion
SELECT [t0].[ID], [t0].[Title], [t2].[Name]
FROM [Post] AS [t0]
INNER JOIN [Relation] AS [t1] ON [t0].[ID] = [t1].[Child]
INNER JOIN [Category] AS [t2] ON [t1].[Parent] = [t2].[ID]
WHERE ((#x1 IS NULL) AND ([t0].[ID] IS NULL)) OR ((#x1 IS NOT NULL) AND ([t0].[ID] IS NOT NULL) AND (#x1 = [t0].[ID]))

Resources