I have a sql:
Doctrine_Query::create()
->select('(t.a+t.b) as c')
->from('mytable t')
->where('t.c > 1');
it raise a "Unknown column c" error;
Anyone can help?
I have a try:
Doctrine_Query::create()
->select('(t.a+t.b) as c')
->from('mytable t')
->orderBy('t.c');
It's OK;
why?
I suspect if you are using MySQL it is because the WHERE clause does not support computed columns, you need to:
a) Repeat (t.a + t.b) > 1 in the where clause
b) use having (t.c > 1) instead of the Where clause
Related
lets say i have a column with many lines but only two values, A and B:
i am trying unsuccessfully to count only lines with A - in a summary calculation for a dashboard (without making a new column for this specific calculation)
the expression which gives me syntax error is this:
count([column] = 'A')
any suggestion?
You'll need to use an if then else construct:
count( if([Column]='A') then ([Column]) else (Null))
You can use IF-THEN-ELSE or CASE-WHEN-THEN-ELSE to create your own count:
sum(
if ([Query Item] = 'A')
then (1)
else (0)
)
or
sum(
case
when [Query Item] = 'A'
then 1
else 0
end
)
I am trying to exchange db::select() with db::table() so I can use pagination but since I have in my query sum() and am getting an error.
My Quest: How to use sum() and order results with Query Builder::table?
My old but working attempt
$query = 'SELECT SUM(votes.votes) AS c, sites.id, sites.user_id, sites.url, sites.type_id, sites.img_src, sites.details, sites.created_at, sites.updated_at
FROM sites
JOIN votes
WHERE sites.id = votes.site_id
GROUP BY sites.id, sites.user_id, sites.url ,sites.type_id, sites.img_src, sites.details, sites.created_at, sites.updated_at
ORDER BY c DESC LIMIT 10');
My new attempt
$test = DB::table('sites')
->join('votes', 'site.id', '=', 'votes.site_id')
->select(\DB::raw('SUM(votes.votes) AS c'), 'sites.id', 'sites.user_id', 'sites.url', 'sites.type_id', 'sites.img_src', 'sites.details', 'sites.created_at', 'sites.updated_at')
->where('sites.id ', '=', 'votes.site_id')
->groupBy('sites.id, sites.user_id, sites.url ,sites.type_id, sites.img_src, sites.details, sites.created_at, sites.updated_at')
->orderBy('c', 'DESC')
->get();
Error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.`url ,sites`.`type_id, sites`.`img_src, sites`.`details, sites`.`created_at, si' at line 1 (SQL: select SUM(votes.votes) AS c, `sites`.`id`, `sites`.`user_id`, `sites`.`url`, `sites`.`type_id`, `sites`.`img_src`, `sites`.`details`, `sites`.`created_at`, `sites`.`updated_at` from `sites` inner join `votes` on `site`.`id` = `votes`.`site_id` group by `sites`.`id, sites`.`user_id, sites`.`url ,sites`.`type_id, sites`.`img_src, sites`.`details, sites`.`created_at, sites`.`updated_at` order by `c` desc) ```
Group by multiple fields
You need to split the string in groupBy method, or Laravel will take it as one field:
->groupBy('sites.id', 'sites.user_id', 'sites.url' ,'sites.type_id', 'sites.img_src', 'sites.details', 'sites.created_at', 'sites.updated_at')
Compare two columns by whereColumn
->where('sites.id ', '=', 'votes.site_id')
will compare the column sites.id with string "votes.site_id", you need to use whereColumn to compare two columns:
->whereColumn('sites.id ', '=', 'votes.site_id')
How can I convert the following complex SQL query to use the Eloquent query builder? I want to use methods such as join() and where(), get() etc.
The below query returns a list of locations along with counts for vouchers that have been redeemed.
select
a.location_name,
'' as dates,
a.places,
sum(netvalue155),
sum(netvalue135) from
(
select
l.id,
l.location_name,
b.places,
case when v.net_value = 155 then 1 else 0 end as netvalue155,
case when v.net_value = 135 then 1 else 0 end as netvalue135
from locations l
left join bookings b on l.id = b.location_id
left join vouchers v on b.voucher_code = v.voucher_code
) a
right join locations l on l.id = a.id
group by a.location_name
EDIT
I am trying the below code, which throws the error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sub.id' in on clause
$subQuery = DB::table('locations')
->select(
'locations.id',
'locations.location_name',
DB::raw('"'.$request->get('dates').'" as dates'),
DB::raw('sum(bookings.id) as number'),
DB::raw('round(sum(bookings.final_price/1.2), 2) as paidbycard'),
DB::raw('case when bookings.voucher_value = 155 then round(sum(bookings.voucher_value/1.2), 2) else 0.00 end as voucher155'),
DB::raw('case when bookings.voucher_value = 135 then round(sum(bookings.voucher_value/1.2), 2) else 0.00 end as voucher135'),
DB::raw('case when bookings.transfer_fee = 10 then round(sum(bookings.transfer_fee/1.2), 2) else 0.00 end as transfer_fee'))
->leftJoin('bookings', 'locations.id', '=', 'bookings.location_id');
$meatBookQuery = DB::table('orders')->select(DB::raw('sum(orders_items.price) as total'))
->join('orders_items', 'orders.id', '=', 'orders_items.order_id')
->where('orders_items.item_name', 'The Meat Book');
$booking = DB::table(DB::raw("({$subQuery->toSql()}) as sub, ({$meatBookQuery->toSql()}) as meatBook"))
->mergeBindings($subQuery)
->mergeBindings($meatBookQuery)
->select('sub.location_name', 'sub.dates', 'sub.number', 'sub.paidbycard', 'sub.voucher155', 'sub.voucher135', 'sub.transfer_fee', DB::raw('round(sum(sub.voucher155 + sub.voucher135 + sub.transfer_fee + sub.paidbycard), 2) as total'), 'meatBook.total')
->leftJoin('locations', 'locations.id', '=', 'sub.id')
->leftJoin('bookings', 'bookings.location_id', '=', 'sub.id')
->groupBy('sub.location_name');
First of all
I often see people asking for how to rebuild a complex SQL query in Laravels Query Builder. But not every operation which is possible in SQL or MySQL is implemented as a function in Laravels Query Builder. This means you can't rebuild every SQL query in Query Builder without using raw SQL.
What does this mean for your SQL query?
Some things like sub queries (the from (select ...) part) and the case when ... part is not implemented in Query Builder. At least therefore you will have to use the raw expression with the DB::raw() function. I'm not sure about the sum() if this is already possible but you will surely find that in the docs.
Other things like joins are implemented as a function:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();
see Laravel Documentation: Queries - Joins
And you can even mix up Query Builder functions with raw expressions:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
see Laravel Documentation: Queries - Raw Expression
Example for a sub query:
$subQuery = DB::table('locations')
->leftJoin('bookings', 'locations.id', '=', 'bookings.location_id')
->leftJoin('vouchers', 'bookings.voucher_code', '=', 'vouchers.voucher_code')
->select('locations.id', 'locations.location_name', 'bookings.places');
$query = DB::table(DB::raw("({$subQuery->toSql()} as sub"))
->mergeBindings($subQuery)
->select(...)
->rightJoin(...)
->groupBy('sub.location_name')
->get();
So you can rebuild some parts of the query in Query Builder and use raw expressions wherever you need to.
To debug a query while you build it Laravels query logging function can be very helpful.
I'm trying to do this:
SELECT
userId, count(userId) as counter
FROM
quicklink
GROUP BY
userId
HAVING
count(*) >= 3'
In doctrine with the querybuilder, I've got this:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
Which gives me this error:
[Semantical Error] line 0, col 103 near 'HAVING count(*)': Error: Cannot group by undefined identification variable.
Really struggling with doctrine. :(
Your SQL is valid, Your query builder statement is invalid
All cause db will execute that query in following order:
1. FROM $query = $this->createQueryBuilder('q')
2. GROUP BY ->groupby('userId') // GROUP BY
3. HAVING ->having('counter >= 3')
4. SELECT ->select('userId, count(userId) as counter')
So as You can see counter is defined after its use in having.
Its SQL Quirk. You can not use definitions from select in where or having statements.
So correct code:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('count(userId) >= 3')
->getQuery();
return $query->getResult();
Do note repetition in having from select
I am going to answer for people who still have this type of error.
First things first, you seem to have translated a native sql query inside a query builder object. More so, you have named your object as q
$query = $this->createQueryBuilder('q');
What this means, in general, is that every condition or grouping etc you have in your logic should address fields of q: q.userId, q.gender, ...
So, if you had written your code like below, you would have avoided your error:
$query = $this->createQueryBuilder('q')
->select('q.userId, count(q.userId) as counter')
->groupby('q.userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
I think you are missing the 'from' statement
$query = "t, count(t.userId) as counter FROM YourBundle:Table t group by t.userId having counter >1 ";
return $this->getEntityManager()->createQuery($query)->getResult();
This should work. You can even do left joins or apply where clausules.
you can define HAVING parameter via setParameter() method as well
$qb->groupBy('userId');
$qb->having('COUNT(*) = :some_count');
$qb->setParameter('some_count', 3);
I'm trying to group my entity by a field (year) and do a count of it.
Code:
public function countYear()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('b.year, COUNT(b.id)')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->addOrderBy('sclr1', 'DESC')
->addGroupBy('b.year');
$query = $qb->getQuery();
die($query->getSQL());
$result = $query->execute();
//die(print_r($result));
return $result;
}
I can't seem to say COUNT(b.id) AS count as it gives an error, and
I do not know what to use as the addOrderby(???, 'DESC') value?
There are many bugs and workarounds required to achieve order by expressions as of v2.3.0 or below:
The order by clause does not support expressions, but you can add a field with the expression to the select and order by it. So it's worth repeating that Tjorriemorrie's own solution actually works:
$qb->select('b.year, COUNT(b.id) AS mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
Doctrine chokes on equality (e.g. =, LIKE, IS NULL) in the select expression. For those cases the only solution I have found is to use a subselect or self-join:
$qb->select('b, (SELECT count(t.id) FROM \My\Entity\Album AS t '.
'WHERE t.id=b.id AND b.title LIKE :search) AS isTitleMatch')
->from('\My\Entity\Album', 'b')
->where('b.title LIKE :search')
->andWhere('b.description LIKE :search')
->orderBy('isTitleMatch', 'DESC');
To suppress the additional field from the result, you can declare it AS HIDDEN. This way you can use it in the order by without having it in the result.
$qb->select('b.year, COUNT(b.id) AS HIDDEN mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
what is the error you get when using COUNT(b.id) AS count? it might be because count is a reserved word. try COUNT(b.id) AS idCount, or similar.
alternatively, try $qb->addOrderby('COUNT(b.id)', 'DESC');.
what is your database system (mysql, postgresql, ...)?
If you want your Repository method to return an Entity you cannot use ->select(), but you can use ->addSelect() with a hidden select.
$qb = $this->createQueryBuilder('q')
->addSelect('COUNT(q.id) AS HIDDEN counter')
->orderBy('counter');
$result = $qb->getQuery()->getResult();
$result will be an entity class object.
Please try this code for ci 2 + doctrine 2
$where = " ";
$order_by = " ";
$row = $this->doctrine->em->createQuery("select a from company_group\models\Post a "
.$where." ".$order_by."")
->setMaxResults($data['limit'])
->setFirstResult($data['offset'])
->getResult();`