Convert a MySql query into Laravel - php

My SQL query is:
SELECT* FROM cubes LEFT JOIN xkvs ON cubes.id=xkvs.cube_id WHERE xkvs.cube_id IS NULL
I tried the method from the laravel documentation but always get an error, that xkvs.cubes_id is an unknown column.
How do I write this correctly?
This is my try:
$cubes=DB::table('cubes')
->leftjoin('xkvs', function ($join) {
$join->on('cubes.id', '=', 'xkvs.cubes_id')
->where('xkvs.cubes_id', '=', null);
})
->get();

DB::table('cubes')
->select('cubes.*')
->leftjoin('xkvs', 'cubes.id', '=', 'xkvs.cubes_id')
->whereNull('xkvs.cube_id')
->get();

Related

Helpe me to convert SQL query to Laravel eloquent

I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();

Laravel remove quotes from variable in database query

I'm constructing a RAW database query with Laravel (5.4) and I'm getting a problem in that laravel is placing quotes in the SQL output for a variable within a join... The result is that mysql thinks that the variable... Which for example would output to 1 or something numeric is a column and outputs error "Cannot find column '1' in ON clause
PROBLEM SQL CLAUSE:
->join('event_jury_sub_detail', function($join) use($userid)
{
$join->on('event_jury_sub_detail.evtpartsub_id', '=', 'event_partsubmissions.id')
->on('event_jury_sub_detail.authoruser_id','=',$userid);
Problem: $userid gets quotes... And becomes "and event_jury_sub_detail.authoruser_id = 1" - Laravel treats it as a column to look up and fails.
If the quotes are removed it works fine... How to resolve this?
FULL QUERY
$tbl_return = DB::table('event_partsubmissions')
->select(DB::raw('event_partsubmissions.*,
users.usr_firstnames,
users.usr_surnames,
users.email,
users.usr_nationality,
users.usr_country,
event_jury_sub_detail.id as evtjurysubdetid,
event_jury_sub_detail.evtjurysubdet_pointsawarded,
event_jury_sub_detail.evtjurysubdet_notes,
event_jury_sub_detail.evtjurysubdet_randomkey
'))
->join('event_participation', 'event_partsubmissions.evtpartsub_evtpartid', '=', 'event_participation.id')
->join('users', 'evtpart_userid', '=', 'users.id')
->join('event_jury_sub_detail', function($join) use($userid)
{
$join->on('event_jury_sub_detail.evtpartsub_id', '=', 'event_partsubmissions.id')
->on('event_jury_sub_detail.authoruser_id','=',$userid);
})
->where('event_partsubmissions.evtpartsub_evtid', '=', $id)
->where('event_partsubmissions.evtpartsub_enabled', '>=', $partlevel)
->where('event_participation.evtpart_enabled', '>=', 1)
->where('event_participation.evtpart_level', '>=', 100)
->where('users.usr_enabled', '>=', 1)
->get();
You can try to use the alias for table joins:
->join('event_jury_sub_detail as ejsd', ...
And use the alias in following places:
->$join->on('ejsd.evtpartsub_id', '=', 'event_partsubmissions.id')
For scalar params in join conditions, you can use DB wrapper like DB::raw($userid):
->on('ejsd.authoruser_id','=',DB::raw($userid));
use DB::raw()
->on(DB::raw("event_jury_sub_detail.authoruser_id = '".$userid."'"))

Native SQL to Query Builder in Laravel5

I have two tables on Laravel 5 and have to use Query Builder. I have already got the sql for it but i am not able to convert it to Query Builder syntax. SQL is
SELECT COUNT(A.cid) FROM `A` WHERE A.cid IN (SELECT `id` FROM `B` WHERE `create_user`='$name') AND `access_time` BETWEEN '$start_data' AND '$end_data'
when I use
DB::table('A')
->join('B', function ($join) {
$join->on('A.id', '=', 'B.cid');
})
->get();
some syntax like this , it's error so how can I turn the native SQL like "IN" into Query Builder ,thanks
Try Below queries and look at result:
$result= DB::table('a')
->select(DB::raw('COUNT(a.cid) as total_cid'))
->join('b', 'a.cid', '=', 'b.id')
->where('b.create_user', $name)
->whereBetween('a.access_time', [$start_data, $end_data])
->first();
Or try this
$result= DB::table('a')
->join('b', 'a.cid', '=', 'b.id')
->where('b.create_user', $name)
->whereBetween('a.access_time', [$start_data, $end_data])
->count();
In your question you asked how to use IN, for IN try something like this:-
$result= DB::table('a')->whereIn('cid', [1,2,3,4]);
This is the syntax for joins in Laravel 5.2:
$result= DB::table('a')
->join('b', 'a.id', '=', 'b.cid')
->select('a.cid')
->where('A.cid', 'like', '%string%') //optional like
->get();

Eloquent - join clause with string value rather than column heading

I have a question regarding join clauses in Eloquent, and whether you can join on a string value rather than a table column.
I have the code below querying a nested set joining parent/child records in a table 'destinations' via a table 'taxonomy'.
The second $join statement in the closure is the one causing an issue; Eloquent assumes this is a column, when I would actually just like to join on t1.parent_type = 'Destination' - ie, t1.parent_type should = a string value, Destination.
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->on('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Is it possible to force Eloquent to do this? I've tried replacing 'Destination' with DB::raw('Destination') but this does not work either.
Thanking you kindly.
Another best way to achieve same is :
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->where('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Replace your on with where
try using DB::raw("'Destination'")

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