Drupal - How to get SUM of rows - php

I want to do a simple select with a SUM of several rows in Drupal, but I can't seem to figure out how to do that. I know there are more ways to do a query in Drupal (one of them is writing the actual query, but I don't want that).
Here is the code I have:
$query = db_select("node","n");
$query->fields("n", array("nid","likes" => "SUM(likes)"));
But apparently Drupal strips my brackets and I get the following error:
1054 Unknown column 'n.SUMlikes' in 'field list'
Could anyone help me? Is there something like $query->sum()?

You'd be best off using an expression:
$query = db_select('node', 'n')
->fields('n', array('nid'));
$query->addExpression('SUM(likes)', 'likes');
The first argument is the expression, the second the alias.
Hope that helps

Related

Laravel eloquent update join with DB::raw() unknown column

I'm trying to run this update statement, but I get this error:
SQLSTATE[HY000]: General error: 1 no such column: table2.id
DB::table('table1')
->join('table2', 'table1.row_hash', '=', 'table2.row_hash')
->where('table1.some_column', '=', 0)
->whereNull('table1.reference_no')
->update([
'table1.column_to_update' => 1,
'table1.column_to_update_2' => 1,
'table1.column_to_update_3' => 1,
'table1.reference_no' => DB::raw('table2.id') <--comment this line out and it works.
]);
If I comment out that one column from the update statement it works. I've tried using various combinations of quotes and backticks inside of the DB::raw() statement, but still get the same error. This post seems to indicate that I'm doing this the right way, but it's not cooperating.
How can I update the value of table1.reference_no to the value of table2.id? I was hoping to accomplish this in one eloquent query as it's a pretty basic SQL statement. Unfortunately I've also tried using just a raw SQL statement, which yielded other errors despite working when running it directly in my mysql client. This is taking entirely too much time for how simple it should be.
Just stumbled over this.
Putting the values in backticks works. Like this:
'table1.reference_no' => DB::raw('`table2`.`id`')

Laravel Query Builder weird column names conversion

I am trying to figure out why is DB::raw() queries are getting sent as lowercases?
Query = DB::('table_name')->select(['is_read as isRead'])->get();
Result = [{ isRead: true }]
But when I do raw its converting it to lowercase
Query = DB::('table_name')->select(DB::raw('is_read as isRead'))->get();
Result = [{ isread: true }]
I have a reason to use DB raw so I really need to figure this thing out.
I'm not able to reproduce the issue you mention... Which version of Laravel are you using?
For instance, if I run the following:
DB::table('users')->select(DB::raw('is_read as isRead'))->get();
I would get the error:
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'is_read' in 'field list' (SQL: select is_read as isRead from users)'
Which is normal because I have no is_read column in my users table. However, you can see in the error that the isRead is not converted to lowercase.
Maybe you can use selectRaw instead:
DB::table('table_name')->selectRaw('is_read as isRead')->get();
The query would be:
select is_read as isRead from `table_name`
Otherwise, could you update your question to provide more information on how to reproduce so your issue with the capitalization.
I can confirm that when using DB:raw (or orderByRaw or any row raw methods) column names get converted to lowercase.
To avoid that, you can try to protect the name with quotes:
Query = DB::('table_name')->select(['is_read as "isRead"'])->get();

Laravel: Left join sql error

I have written a sql query using Laravel, but I am not understanding, why the error is creating! The codes are given below,
The join operation:
MeetingRoom::select('mr_id')
->leftJoin('meetingroomhistory',function($join)
{
$join->on('country','=',Session::get('country'));
$join->on('location','=',Session::get('location'));
$join->on('building','=',Session::get('building'));
$join->on('floor','=',Session::get('floor'));
$join->on('name_of_mr','=',Session::get('room'));
})
->where('meetingroom.id','=','meetingroomhistory.mr_id')
->get();
The error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Bangladesh' in
'on clause' (SQL: select `mr_id` from `meetingroom` left join
`meetingroomhistory` on `country` = `Bangladesh` and `location` =
`Dhaka` and `building` = `Uttara` and `floor` = `3` and `name_of_mr` =
`1` where `meetingroom`.`id` = meetingroomhistory.mr_id)
But if I run the query manually to change this syntax `Bangladesh` to "Bangladesh" using phpmyadmin so it runs well and show me the result. Please someone let me know, how can I fix it?
I think you've confused the where part and the join part.
$join->on($x, $y) statements are for connecting your tables together. Both $x and $y should be names of columns in your tables - that is why Laravel is adding backticks to them.
$where() statements are for comparing with values that you supply. Your Session::get() calls indicate that's what you're doing.
Here's a suggested rewrite, but it may need to be tweaked to suit your exact needs.
MeetingRoom::select('mr_id')
->leftJoin('meetingroomhistory', 'meetingroom.id', '=', 'meetingroomhistory.mr_id')
->$where('meetingroom.country','=',Session::get('country'))
->$where('meetingroom.location','=',Session::get('location'))
->$where('meetingroom.building','=',Session::get('building'))
->$where('meetingroom.floor','=',Session::get('floor'))
->$where('meetingroom.name_of_mr','=',Session::get('room'))
->get();
I assumed the country, location, etc. columns are part of the meetingroom table, if not you can just change them to $where('meetingroomhistory.country', ...) and so on instead.
Finally, I'm not sure why you're selecting only one value, but of course, that's up to you. If you need only a single cell, you can use pluck(), and if you need a lot of single results you could do lists().
I think you should try this.
MeetingRoom::select('mr_id')
->join('meetingroomhistory', function($join)
{
$join->on('meetingroom.id','=','meetingroomhistory.mr_id')
->where('meetingroomhistory.country','=',Session::get('country'));
->where('meetingroomhistory.location','=',Session::get('location'));
->where('meetingroomhistory.building','=',Session::get('building'));
->where('meetingroomhistory.floor','=',Session::get('floor'));
->where('meetingroomhistory.name_of_mr','=',Session::get('room'));
})
->get();

Laravel 4 query builder - not null column not found

Route::get('/test', function(){
return DB::table('table')->where_not_null('column')->get();
});
In Laravel 4 I have the following route, obviously with table and column replaced. I had it in the controller but it wasn't working, so I moved it to a test route.
The error I am getting is:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '_not_null' in 'where clause' (SQL: select * from `table` where `_not_null` = column)
https://tower.la.utexas.edu/docs/database/fluent#where
Documentation says:
return DB::table('table')->where_null('column')->get();
It should be
return DB::table('table')->whereNull('column')->get();
Or
return DB::table('table')->whereNotNull('column')->get();
You have used where_not_null.This is the right reference.
See the proper writing for that: http://laravel.com/docs/queries#selects
DB::table('table')->whereNotNull('column')->get();
The documentation states that following the table declaration you should put the query builder information, where_null, where_not_null, where_in.
However that doesn't work. I'm not sure why, it makes no sense, and is frustrating. However, this does work.
return DB::table('user')->whereuserName('not_null')->get();
By placing the column name where the documentation says to put the query, and the query where the documentation says to put the column you are able to execute your query. To note, camel case is converted to snake case in the query, so the column has to be named user_name.
I am posting this because I attempted googling it and was not able to find anything.

Zend Framework 2 and SELECT count(*) query

I'm trying to do a query like this using Zend Framework 2:
SELECT count(*) as num FROM mytable
Here's the code I'm using to build my select statement (bear in mind I've imported the necessary classes):
$select = new Select();
$select->from('mytable')
->columns(array('num'=>'count(*)'), false);
This code doesn't work because the resulting query is as follows:
SELECT [count(*)] AS [num] FROM [mytable]
...which throws the following error:
Invalid column name 'count(*)'
This is caused by the square brackets around count(*). How can I get this to work properly, basically to have count(*) instead of [count(*)] in the SQL. Also, I know that you can do it with just a regular query, but I need this to work with the Select object. As far as I know, this used to work with the previous versions of Zend, I've seen plenty of solutions for those, but nothing for Zend Framework 2.
Somebody on another forum was kind enough to give me the answer for this. This is how it's done:
$select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
Yes, without new \Zend\Db\Sql\Expression('COUNT(*)'), just COUNT(*) leads to the following error statement:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'albs.COUNT(*)' in 'field list'
Having the
new \Zend\Db\Sql\Expression('COUNT(*)')
resolved it.
Could you try this code?
$this->num = $select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
return $this->num;

Categories