Change join query to laravel - php

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();

Related

join with multiple conditions in Laravel

I'm trying to join two tables using more than one condition. The following query is not working because of the second join condition.
$all_update = DB::table('posts as p')
->join('cprefs as c','p.qatype', '=', 'c.qatype')
->where('c.wwide', '=', 'p.wwide') //second join condition
->where('c.user_id', $u_id)
->where('p.arank', 1)
->get();
The where() functions expects the last parameter to be a parameter where as you are passing in a column name.
To compare two columns you should use the whereColumn method.
With that in mind, you could also write your code like below:
$all_update = DB::table('posts as p')
->join('cprefs as c','p.qatype', '=', 'c.qatype')
->whereColumn('c.wwide', '=', 'p.wwide') //second join condition
->where('c.user_id', $u_id)
->where('p.arank', 1)
->get();
However, this would only work properly if the the join is an INNER JOIN which is true in your case.
The correct method to add multiple join clauses is as below
$all_update = DB::table('posts as p')
->join('cprefs as c', function($q) {
$q->on('p.qatype', '=', 'c.qatype')
->on('c.wwide', '=', 'p.wwide'); //second join condition
})
->where('c.user_id', $u_id)
->where('p.arank', 1)
->get();
Just use this one.
You need the keyword join to use multiple join condition. Irrespective of table.
$all_update = DB::table('posts as p')
->join('cprefs as c','p.qatype', '=', 'c.qatype')
->join('cprefs as c2','p.wwide', '=', 'c2.wwide') //second join condition
->where('c.user_id', $u_id)
->where('p.arank', 1)
->get();

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')

Laravel 5.4 query builder having issues with groupBy

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')

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

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();

Categories