Laravel 5.4 query builder having issues with groupBy - php

I'm trying to convert this query to query builder in Laravel 5.4:
SELECT
oc.id,
oc.name,
oat.user_id,
p.first_name,
p.last_name
FROM
oauth_clients oc
LEFT JOIN oauth_access_tokens oat ON oc.id = oat.client_id
JOIN users u on u.id = oat.user_id
JOIN people p on p.id = u.person_id
WHERE oc.revoked = false AND oc.password_client = true
GROUP BY oc.id, oat.user_id
And getting this error barf: Argument 1 passed to Illuminate\Database\Connection::prepareBindings() must be of the type array, string given, called in /var/www/html/source/luniverse/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 648 and defined
This is my attempt at it (one of many):
$tokens = DB::select('oc.id','oc.name','oat.user_id','p.first_name','p.last_name')
->from('oauth_clients as oc')
->leftJoin('oauth_access_tokens as oat', 'oc.id', '=', 'oat.client_id')
->join('users as u', 'u.id', '=', 'oat.user_id')
->join('people as p', 'p.id', '=', 'u.person_id')
->where('oc.revoked', '=', 'false')
->where('oc.password_client', '=', 'true')
->groupBy('oc.id')
->groupBy('oat.user_id')
->get();
The database config is set to strict mode, but that doesn't exactly seem to explain that particular error. The raw query runs fine in a DB gui.

Change the groupby code like
$tokens = DB::select('oc.id','oc.name','oat.user_id','p.first_name','p.last_name')
->from('oauth_clients as oc')
->leftJoin('oauth_access_tokens as oat', 'oc.id', '=', 'oat.client_id')
->join('users as u', 'u.id', '=', 'oat.user_id')
->join('people as p', 'p.id', '=', 'u.person_id')
->where('oc.revoked', '=', 'false')
->where('oc.password_client', '=', 'true')
->groupBy('oc.id','oat.user_id')
->get();

DB::select() executes a query, you have to use DB::table():
DB::table('oauth_clients as oc')
->select('oc.id','oc.name','oat.user_id','p.first_name','p.last_name')

Related

Laravel join query not working when passing a variable

I want to execute a join statment in laravel by passing a php varaiable,Bit its not working when passing a varibale. Following is my code
$loc_services = Clinic::select('*')
->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
->join('services', 'services.serviceID', '=', $services_id)
->get();
I tried to execute it as statment and got the following
select * from `clinics` inner join `locations` on `locations`.`clinicID` = `clinics`.`clinicID` inner join `location_services` on `location_services`.`locationID` = `locations`.`locationID` inner join `services` on `services`.`serviceID` = `10`
When i directly executed it in phpmyadmin it returns fllowing error
Column not found: 1054 Unknown column '10' in 'on clause', i found that error is triggering because `10` is inside `''` quotes, how can i execute this
You have to pass $services_id in where cloud not in join on
$loc_services = Clinic::select('*')
->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
->join('services', 'services.serviceID', '=', 'clinics.services_id')//service_id column in Clinic
->where('services.serviceID',$services_id)
->get();
The third parameter in join will be treated as column. If you want to join the column with a specific value, you can use closure like this:
$loc_services = Clinic::select('*')
->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
->join('services', function($join) use ($service_id) {
$join->where('services.serviceID', $service_id);
})
->get();
The Raw sql will be:
inner join `services` on `services`.`serviceID` = 10

Mysql Raw Count Only

I use to PHP and Laravel Framework on my project.
Above code works perfectly
$users = User::select([
'users.id',
'users.name',
'users.company',
'users.country',
'users.city',
'users.email',
'users.created_at',
\DB::raw('SUM(reservations.dolar) as dolar'),
\DB::raw('count(reservations.confirmation) as confirmation'),
])->join('reservations','reservations.user_id','=','users.id')
->groupBy('reservations.user_id');
Now Counting all reservation.confirmation column but I want to count only reservation.confirmation column values 1
How I can edit
\DB::raw('count(reservations.confirmation) as confirmation'),
this code
Have you tried see in https://laravel.com/docs/5.6/queries#joins in the section "Advanced Join Clauses", you can add condition in Join function
$users = User::select([
'users.id',
'users.name',
'users.company',
'users.country',
'users.city',
'users.email',
'users.created_at',
\DB::raw('SUM(reservations.dolar) as dolar'),
\DB::raw('count(reservations.confirmation) as confirmation'),
])->join('reservations', function ($join) {
$join->on('reservations.user_id', '=', 'users.id')
->where('reservations.confirmation', '=', 1);
})->groupBy('reservations.user_id');
If you want have all sum dolar not depends with confirmation,
you can use 'case' statement:
\DB::raw('sum(case when reservations.confirmation=1 then 1 else 0 end) as confirmation')
or subquery:
\DB::raw('(Select count(*) FROM reservations WHERE user_id = users.id AND confirmation=1) as confirmation')

Change join query to laravel

I have a mysql query
SELECT a.`head_id` AS "Headid",a.`name` AS "HeadName", b.`id` AS "Emp_ID",b.`name` AS "Emp_name" FROM users a join users b ON a.id=b.head_id where a.`head_id`=63 or b.`id`=63
How can i convert this query to laravel?
$users = DB::table('users a')
->join('users b', 'a.id', '=', 'b.head_id')
->select('a.head_id as Headid','a.name AS HeadName','b.name AS Emp_name','b.name AS Emp_name')
->get();
but bad luck this is not working.please help me.
Your query builder looks fine just add where filters as per your plain query
$users = DB::table('users as a')
->join('users as b', 'a.id', '=', 'b.head_id')
->select('a.head_id as Headid','a.name AS HeadName','b.name AS Emp_name','b.name AS Emp_name')
->where('a.head_id', '=', 63)
->orWhere('b.id','=', 63)
->get();

how to write sql join query in laravel 5.2

To make the report i need to write a join query. I wrote the join query in sql now, i need to write the same query in laravel 5.2.
My sql query is given below.
SELECT a.accountID, a.deviceID, b.description, a.timestamp, a.latitude, a.longitude, a.speedKPH as speed, a.heading, a.altitude, a.address, a.distanceKM as distance, a.odometerKM as odometer, a.IbatVolts, a.EbatVolts, a.ITempr, a.fuelLevel, a.inputState, a.IgnRuntime, a.GPSFixType, a.GPSPDOP, a.AlertType, a.speedLimitKPH, a.isTollRoad
FROM eventdata as a, device as b
WHERE a.deviceID = '$deviceID'
AND a.accountID = '$accountID'
AND a.timestamp >= $dt1
AND a.timestamp <= $dt2
AND a.deviceID=b.deviceID
ORDER BY timestamp DESC
and i tried to write it in laravel also. the query is given below
DB::table('device as b')
->join('eventdata as a', 'a.deviceID', '=', 'b.deviceID')
->where('a.deviceID', '=', '$deviceID')
->where('a.accountID', '=', '$accountID')
->where('a.timestamp', '>=', '$dt1')
->where('a.timestamp', '<=', '$dt2')
->select('a.accountID', 'a.deviceID', 'b.description', 'a.timestamp',
'a.latitude', 'a.longitude', 'a.speed', 'a.heading', 'a.altitude', 'a.address', 'a.distanceKM as distance', 'a.odometerKM as odometer', 'a.IbatVolts', 'a.EbatVolts', 'a.ITempr', 'a.fuelLevel', 'a.inputState', 'a.IgnRuntime', 'GPSFixType', 'a.GPSPDOP', 'a.AlterType', 'a.speedLimitKPH', 'a.isTollRoad')->get():
Is this right? Can anyone tell me and help me to write the correct query.
The join syntax in laravel 5.2 is:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
and you are using the same. In case you are facing any issue than you can print the raw sql query by using:
DB::enableQueryLog();
// Your query
$queries = DB::getQueryLog();
print_r($queries); // it will print raw sql query in prepared statement style

Complicated Laravel Query leftjoin a made query

Right now I want to have the sum of Sueldo in a column grouped by idEmpleado of table recibo. Im not sure if I can put the DB::table inside the left join. if not how could I call that table in a query to make a join with the information of the empleado.
Here is what I have so far
$pagos = DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftJoin(
DB::table('recibos')
->leftJoin('empleado', 'empleado.idEmpleado', '=', 'recibos.rec_idEmpleado_FK')
->select(DB::raw('idRecibos, rec_idEmpleado_FK, SUM(SueldoBase) as Restante'))
->groupBy('rec_idEmpleado_FK')
->get()
,'recibos', 'recibos.rec_idEmpleado_FK', '=', 'empleado.idEmpleado')
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();
I'm getting an error ErrorException with message :
Array to string conversion
I'm suppose its because I'm trying to make a leftjoin of a query im making there. Dunno Im knid of new to this. Any suggestions ?
With the help of the answer in the commnets I got to this Query,
DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftjoin(
DB::raw('SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
INNER JOIN empleado ON rec_idEmpleado_FK = idEmpleado
GROUP BY rec_idEmpleado_FK'),
function($join)
{
$join->on('idEmpleado', '=', 'rec_idEmpleado_FK');
})
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();
But still get the error:
check the manual that corresponds to your MySQL server version for the right syntax to use near
SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
Any ideas why?
Ok I finally got the answer. I forgot to put the name to the inner query here is my answer. I hope it helps. I based my answer in the link that Chelsea gave me. Thanks
$pagos = DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftjoin(
DB::raw('(SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
INNER JOIN empleado ON rec_idEmpleado_FK = idEmpleado
GROUP BY rec_idEmpleado_FK) AS recibos1'),
function($join)
{
$join->on('idEmpleado', '=', 'rec_idEmpleado_FK');
})
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();

Categories