Query to fetch multiple column from multiple table in symfony doctrine - symfony-3.1

I want to fetch data from multiple tables but i am not getting the correct query in symfony3 doctrine. Please help me.
I wrote my doctrine query as follows -
$q = $this-> getDoctrine()-> getManager();
$query = $q->createQuery('
SELECT p.firstname , p.lastname , l.language
from UserBundle:Post p
from UserBundle:Language l
from UserBundle:UserLanguage u
where p.id = u.id and l.id = u.languageid
');
return $queryBuilder->getQuery()->getResult();
}

I am Finally able to solve this issue. This is the dql query to fetch different columns from multiple table with given condition.
$em = $this -> getDoctrine()->getManager();
$res = $em->createQuery(' SELECT p.firstname , p.lastname , l.language from UserBundle:Post p Join UserBundle:UserLanguage u with p.id = u.userid join UserBundle:Language l with l.id = u.languageid');
$result = $res->getResult();
return $this->render('UserBundle:Default:showLanguage.html.twig', array('user' => $result));

Related

Applying where condition to each value selected in Linq query with Groupby in it

In this linq query I need to apply where condition for selecting only tiertype .I have tried the following but getting error in the where condition of tiertype.The error is "ti in ti.ImageVersion ti does not exist in current context.
var result = (from p in _context.Product
join ti in _context.TierImageMap on p.Id equals ti.ProductId
join t in _context.Tiers on ti.TierType equals t.Id
where (p.Id == productname)
orderby ti.ReleaseVersion descending
group new { ti, t } by new { ti.ImageName, t.TierType,ti.ImageVersion } into cities
select new
{
ReleaseVersion = string.Join(",", (from n in cities select n.ti.ReleaseVersion).Distinct().Take(3)),
ImageName = string.Join(",", (from n in cities select n.ti.ImageName).Distinct()),
TierType = string.Join(",", (from n in cities select n.t.TierType).Where(ti.ImageVersion== imageversion).Distinct())
//String.Format(ti.ReleaseVersion, ", ").GroupBy.OrderByDescending( ti.ImagDESeName ) as Releaseversion,
//String.Format(t.TierType, ", ").GroupBy.OrderByDescending( ti.ImageName ) as Tiertype
}).ToList().Distinct();
await _context.SaveChangesAsync();

LINQ to Entities returning NULL when searching by GUID

I have a LINQ to Entities Query that is suppose to return a specific resultset based on the GUID provided.
[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)]
public List<OrderDetails> GetOrderDetailsByGUID(Guid OrderID)
{
var listit =(from OV in EC.OrderProductVariants
join O in EC.Orders on OV.OrderId equals O.Id
join PV in EC.ProductVariants on OV.ProductVariantId equals PV.Id
join P in EC.Products on PV.ProductId equals P.Id
join CT in EC.Customers on O.CustomerId equals CT.Id
join AD in EC.Addresses on CT.BillingAddress_Id equals AD.Id
where O.OrderGuid == OrderID
select new OrderDetails
{
OrderID = O.OrderGuid,
Company = AD.Company,
ShippingMethod = O.ShippingMethod,
Product = P.Name,
QuantityOnOrder = OV.Quantity
}
).ToList();
return listit;
}
It Returns NULL, can anyone tell me what I am doing wrong?
All solution that could work in a scenario like this is to create a view and do just a one liner code to access it
var q = EC.OrderProductVariants.SingleOrDefault(u => u.OrderGuid.Equals(guid));

Search ranking in LINQ, MVC 3 and Entity Framework

Previously in SQL I would use something like this to rank my search results:
--search product name
SELECT tblProduct.ProductID, 20 AS Ranking
FROM tblProduct
INNER JOIN tblManufacturer ON tblProduct.ManufacturerID=tblManufacturer.ManufacturerID
LEFT OUTER JOIN tblProductCollection ON tblProduct.CollectionID=tblProductCollection.CollectionID
WHERE tblManufacturer.Name + ISNULL(' ' + tblProductCollection.CollectionName, '') + ' ' + tblProduct.Name LIKE '%' + #term + '%' AND tblProduct.Active = 1
UNION ALL
--search product exact name
SELECT tblProduct.ProductID, 200 AS Ranking
FROM tblProduct WHERE Name = '%' + term AND tblProduct.Active = 1
UNION ALL
This example says if your search term is contained in the name: 20 is the rank, if you match the name exactly: 200 is the rank. Union the tables together, order by Ranking(descending) and hey presto!
I'm trying to do this in LINQ this time round and am unsure how to go about doing it, to be honest I'm unsure my previous example was the best way to do it originally.
So, I have a Product Entity mapped to my database and I've added a property in my partial class called SearchRanking:
var query = from p in db.Products
where p.Name.Contains(term)
select p;
var query2 = from p in db.Products
where p.Name.ToLower() == term
select p;
Somehow I need to set the properties like so:
var query = from p in db.Products
where p.Name.Contains(term)
select p, p.SearchRanking = 20;
var query2 = from p in db.Products
where p.Name.ToLower() == term
select p, p.SearchRanking = 200;
Am I on the right track?
If you're wanting to create a new anonymous type you could do this:
var foundProducts = (from p in products
where p.Name.Contains(term)
select new Product
{
ProductId = p.ProductId,
Category = p.Category,
Brand = p.Brand,
SearchRanking = p.Name.ToLower() == term ? 200 : 20
}).OrderBy(s => s.SearchRanking).Take(20);
I would do something like this;
var query = (from p in db.Products
where p.Name.Contains(term)
select p).ToList().ForEach(p => p.SearchRanking = 20);
A more efficient way would be to;
var query = (from p in db.Products
where p.Name.Contains(term)
select new Product
{
Id = p.Id,
//set the other props here
SearchRanking = 20
}).ToList();

LINQ convert DateTime to string

List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();
The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?
Exception error:
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim
In other words, return the date itself and convert it to a string after it executes on SQL side:
(
select new { Username = u.Username,
PostingDate = c.Date
[...]
})
.ToList() // runs on SQL and returns to the application
.Select(o => // is not generating a SQL, it is running on the app
new Post { Username = o.Username,
PostingDate = o.PostingDate.ToString(),
[...]
})
You can remedy your problem by projecting into an anonymous type, and then at a later step project into Post after the data has already been returned from the DB.
(from ....
select new { /* stuff */, Date = c.Date })
.AsEnumerable()
.Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
.ToList();
However, given that you have a property called PostingDate, the original source being a date, I would recommend your revise your object to actually keep the value as a DateTime instead of a string.
I dont think this can be done in a direct way.
var list =
select new Post { Username = u.Username, PostingDate = SqlFunctions.StringConvert(c.Date), Data = c.Comment }
from
(from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending).AsEnumerable()
).ToList();
Also with EF4 you can try something like this:
List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = SqlFunctions.DateName(c.Date), Data = c.Comment }
).ToList();

EF 4.0 Linq to Enity query

Hi guys i need to replicate this SQL query in Linq to Entity
select * from Subscriber a
inner join User b on a.UserId = b.Id
where b.Username = 'Name'
May be some one may help.
Try this:
var query = from s in context.Subscribers.Include("User")
where s.User.Username == "Name"
select s;
This suppose that Subscriber has navigation property User referencing the user instance.
If you wan to use join (which is not needed) you can use this for inner join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id
where u.Username == "Name"
select new
{
Subscriber = s,
User = u
};
or this for left outer join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id into x
where u.Username == "Name"
from y in x.DefaultIfEmpty()
select new
{
Subscriber = s
User = y,
};

Resources