How to use multiple condition in leftjoin with raw query in laravel5 - php

I need to join two table to fetch data with multiple condition on leftjoin but
i am getting this error. Not enough arguments for the on clause I am using laravel5.2. How to use raw query with leftjoin multiple condition.
$activityDetail = DB::table('table1 as UA')
->selectRaw('SUM(UA.total_calory) as total_calory,
SUM(UA.flight_descend) as flight_descend,date('.$tz_start_date.') as start_date')
->leftjoin('table2 as LC',function($join) use($tz_lccreated_date,$dateRange){
$join->on('LC.user_id_fk','=','UA.user_id_fk');
$join->on('LC.is_active','=',DB::raw('1'));
$join->on(' date('.DB::raw($tz_lccreated_date).') '.DB::raw($dateRange));
})
->whereRaw(' date('.$tz_start_date.') '.$dateRange)
->where('UA.user_id_fk','=',base64_decode($params['uid']))
->groupBy(DB::raw('date('.$tz_start_date.')'))
->get();
Raw query is
select SUM(UA.total_calory) as total_calory,
SUM(UA.flight_descend) as flight_descend,
date(CONVERT_TZ(UA.start_date,"+00:00","+05:30")) as start_date
from `table1` as `UA`
left join `table2` as `LC`
on `LC`.`user_id_fk` = `UA`.`user_id_fk` and `LC`.`is_active` = 1
and `date(CONVERT_TZ(LC`.`created_date,"+00:00","+05:30"))` = `current_date`
where date(CONVERT_TZ(UA.start_date,"+00:00","+05:30")) = current_date
and `UA`.`user_id_fk` = 411
group by date(CONVERT_TZ(UA.start_date,"+00:00","+05:30"))

I have resolved my problem, after a lots of analysis, i am not getting any kind of solution of raw query in join clause then i am using subquery and resolve my problem.
$mannualLoggedQuery = 'IFNULL((select sum(calory) as cal from table2 as LC where LC.user_id_fk = "'.base64_decode($params['uid']).'" and date('.$tz_lccreated_date.')'.$dateRange.'),0)';
$activityDetail = DB::table('table1 as UA')->selectRaw('SUM(UA.total_calory) + '.$mannualLoggedQuery.' as total_calory,
date('.$tz_start_date.') as start_date')
->where('UA.user_id_fk','=',base64_decode($params['uid']))
->whereRaw('date('.$tz_start_date.') '.$dateRange)
->groupBy(DB::raw('date('.$tz_start_date.')'))
->get();

Related

raw query join left with select to laravel 8 query

i'm using raw query on my laravel function, and i wanna make it into laravel query builder, but i really have no idea how to do it, i've read laravel documentary about advanced join clause or subquery joins, but still cant figuring it out how to convert it
raw query :
$buku = DB::select(
DB::raw('
SELECT buku.*, kategory, tag
FROM buku
LEFT JOIN kategori_buku ON buku.id_kategori = kategori_buku.id
LEFT JOIN detail_buku_tag ON buku.id = detail_buku_tag.id_buku
LEFT JOIN (SELECT tag_buku.id, GROUP_CONCAT(tag) AS tag FROM tag_buku) AS tag_buku ON tag_buku.id = detail_buku_tag.id_tag
GROUP BY buku.id')
);
there some sql chaining issue. #Ramiz Kongulov forget to split group by clause try this.
$buku = \DB::table('buku')
->select(['buku.*','kategory.*', 'tag.*'])
->leftJoin('kategori_buku', 'kategori_buku.id', '=', 'buku.id_kategori')
->leftJoin('detail_buku_tag', 'detail_buku_tag.id_buku', '=', 'buku.id')
->leftJoin(\DB::raw('(SELECT tag_buku.id, GROUP_CONCAT(tag) AS tag FROM tag_buku) AS tag_buku'),
'tag_buku.id', '=', 'detail_buku_tag.id_tag')
->groupBy('buku.id')
->get();
try this
$buku = \DB::table('buku')
->select([
'buku.*',
'kategory.*',
'tag.*'
])
->leftJoin('kategori_buku', 'kategori_buku.id', '=', 'buku.id_kategori')
->leftJoin('detail_buku_tag', 'detail_buku_tag.id_buku', '=', 'buku.id')
->leftJoin(DB::raw('SELECT tag_buku.id, GROUP_CONCAT(tag) AS tag FROM tag_buku) AS tag_buku ON tag_buku.id = detail_buku_tag.id_tag GROUP BY buku.id'))
->get();

This row query working properly please help to change it eloquent query

SELECT `foduu_listing`.`id`,`foduu_listing_filedetail`.`primary`, `foduu_listing`.`name`,`foduu_listing`.`filemanager_id`,`foduu_filemanager`.`filepath`,`foduu_detail_orders`.`listing_id`, COUNT(`foduu_detail_orders`.`listing_id`) AS count,SUM(`foduu_detail_orders`.`total`) AS total
FROM foduu_listing
left join `foduu_detail_orders` on `foduu_listing`.`id` = `foduu_detail_orders`.`listing_id`
left join `foduu_listing_filedetail` on `foduu_listing`.`id` = `foduu_listing_filedetail`.`listing_id`
left join `foduu_filemanager` on `foduu_listing`.`filemanager_id` = `foduu_filemanager`.`id`
where `foduu_detail_orders`.`listing_id` = 593
I would do it like this:
DB::table('foduu_listing')->select('foduu_listing.id`,foduu_listing_filedetail.primary, foduu_listing.name,foduu_listing.filemanager_id,foduu_filemanager.filepath,foduu_detail_orders.listing_id')
->leftJoin('foduu_detail_orders', 'foduu_listing.id', '=', 'foduu_detail_orders.listing_id')
->leftJoin('foduu_listing_filedetail', 'foduu_listing.id', '=', 'foduu_listing_filedetail.listing_id')
->leftJoin('foduu_filemanager', 'foduu_listing.filemanager_id', '=', 'foduu_filemanager.id')
->selectRaw('COUNT(`foduu_detail_orders`.`listing_id`) AS count')
->selectRaw('SUM(`foduu_detail_orders`.`total`) AS total')
->where('foduu_detail_orders.listing_id', 593)
->get();
If instead of calling get at the end you call toSql you can check the query generated:
select `foduu_listing`.`id``,foduu_listing_filedetail`.`primary, foduu_listing`.`name,foduu_listing`.`filemanager_id,foduu_filemanager`.`filepath,foduu_detail_orders`.`listing_id`, COUNT(`foduu_detail_orders`.`listing_id`) AS count, SUM(`foduu_detail_orders`.`total`) AS total from `foduu_listing` left join `foduu_detail_orders` on `foduu_listing`.`id` = `foduu_detail_orders`.`listing_id` left join `foduu_listing_filedetail` on `foduu_listing`.`id` = `foduu_listing_filedetail`.`listing_id` left join `foduu_filemanager` on `foduu_listing`.`filemanager_id` = `foduu_filemanager`.`id` where `foduu_detail_orders`.`listing_id` = ?
However you are not making use of Laravel tools if you just translate your queries from raw SQL to Eloquent like this, you should define your models and your relationships properly and then make use of that for querying your data.

Laravel query builder with joins

I am blocked in the conversion of my raw sql query to laravel query builder. Can someone give me a hand on the issue?
select p.name, p.`type`, p.`status`, p.state, ps1.* from pos_session ps1 right join pos p on ps1.pos_id = p.id where ps1.id = (select max(ps0.id) from pos_session ps0 where ps0.pos_id = ps1.pos_id) or p.site_id = '2' order by ps1.pos_id;
Try following query:
DB::table('pos_session AS ps1')
->select('p.name','p.type','p.status','p.state','ps1.*')
->rightJoin('pos AS p','ps1.pos_id','=','p.id')
->where('ps1.id','=',function($query){
$query->select(DB::raw('MAX(ps0.id)'))
->from('pos_session AS ps0')
->where('ps0.pos_id','=','ps1.pos_id');
})
->orWhere('p.site_id','=',2)
->orderBy('ps1.pos_id')
->get();
you can achieve the results through join as well:
DB::table('pos_session AS ps1')
->select('p.name','p.type','p.status','p.state','ps1.*')
->rightJoin('pos AS p','ps1.pos_id','=','p.id')
->join('pos_session AS ps0', 'ps0.pos_id', '=', 'ps1.pos_id')
->where('ps1.id','=',DB::raw('MAX(ps0.id)'))
->orWhere('p.site_id','=',2)
->orderBy('ps1.pos_id')
->get();
Hope it helped :)

laravel DB query select multiple tables without joining

I have a Raw SQL query here and what to know how to write this Raw query in laravel query builder
Here is the Raw Query :
SELECT tbl_stock.* , series.*, series_size.*, tbl_size.* FROM
tbl_stock , series, series_size, tbl_size
WHERE
tbl_stock.series_id = series.series_id AND
tbl_stock.size_id = series_size.size_id AND
tbl_stock.size_id = tbl_size.size_id
I have Tried DB Query builder laravel but getting exception
$stock_info = DB::table(['tbl_stock', 'shades'])->get();
This gives me this
Array to String Conversion Exception
THANKS IN ADVANCE
First of all, you should replace your archaic join syntax with modern syntax:
SELECT
t1.*,
t2.*,
t3.*,
t4.*
FROM tbl_stock t1
INNER JOIN series t2
ON t1.series_id = t2.series_id
INNER JOIN series_size t3
ON t1.size_id = t3.size_id
INNER JOIN tbl_size t4
ON t1.size_id = t4.size_id;
Then, use Laravel's query builder syntax to build your query in PHP code:
$stocks = DB::table('tbl_stock')
->join('series', 'tbl_stock.series_id', '=', 'series.series_id')
->join('series_size', 'tbl_stock.size_id', '=', 'series_size.size_id')
->join('tbl_size', 'tbl_stock.size_id', '=', 'tbl_size.size_id')
->select('tbl_stock.*', 'series.*', 'series_size.*', 'tbl_size.*')
->get();

Different results using same query with DB::raw and Eloquent

I'm getting some unexpected results when running an Eloquent join query. I get two different results from using the exact same query. One running with DB::raw(), the second with Eloquent.
In the Eloquent query, the Users that matches the
where squad_user.leave_time >= seasons.start_time
are missing and will not be included in the result set. The users that matches the
or squad_user.leave is null
will be included, however.
That's the only difference in the results from the two queries. The raw query actually produces the desired result set.
What really puzzles me is, if I check the query logs, both Laravel's and MySQL, I get the exact same query when running both the raw and Eloquent query.
Raw query (the actual query i get from the query log when running the Eloquent query)
return \DB::select(\DB::raw('
select users.*
from users
inner join squad_user on users.id = squad_user.user_id
inner join seasons on squad_user.squad_id = seasons.squad_id
where squad_user.join_time <= seasons.end_time
and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null)
and seasons.id = :seasonId
'),
['seasonId' => 3]
);
Eloquent query
return User::join('squad_user', 'users.id', '=', 'squad_user.user_id')
->join('seasons', 'squad_user.squad_id', '=', 'seasons.squad_id')
->where('squad_user.join_time', '<=', 'seasons.end_time')
->where(function ($query)
{
$query->where('squad_user.leave_time', '>=', 'seasons.start_time')
->orWhereNull('squad_user.leave_time');
})
->where('seasons.id', 3)
->get(['users.*']);
Laravel's Eloquent query log
select `users`.*
from `users`
inner join `squad_user` on `users`.`id` = `squad_user`.`user_id`
inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id`
where `squad_user`.`join_time` <= seasons.end_time
and (`squad_user`.`leave_time` >= seasons.start_time or `squad_user`.`leave_time` is null)
and `seasons`.`id` = 3
{"bindings":["seasons.end_time","seasons.start_time",3],"time":0.38,"name":"mysql"}
MySQL's general_log on the Eloquent query
select `users`.*
from `users`
inner join `squad_user` on `users`.`id` = `squad_user`.`user_id`
inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id`
where `squad_user`.`join_time` <= ?
and (`squad_user`.`leave_time` >= ? or `squad_user`.`leave_time` is null)
and `seasons`.`id` = ?
MySQL's general_log on the Raw query
select users.*
from users
inner join squad_user on users.id = squad_user.user_id
inner join seasons on squad_user.squad_id = seasons.squad_id
where squad_user.join_time <= seasons.end_time
and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null)
and seasons.id = ?
I would appreciate any pointers here, as I am very lost.
where binds 3rd param and treats it usually as a string, unless you tell it not to by using raw statement. DB::raw or whereRaw will work for you:
return User::join('squad_user', 'users.id', '=', 'squad_user.user_id')
->join('seasons', 'squad_user.squad_id', '=', 'seasons.squad_id')
->where('squad_user.join_time', '<=', DB::raw('seasons.end_time'))
->where(function ($query)
{
$query->where('squad_user.leave_time', '>=', DB::raw('seasons.start_time'))
->orWhereNull('squad_user.leave_time');
})
->where('seasons.id', 3)
->get(['users.*']);
Since Laravel Verion 5.2 you can also use whereColumn to verify that two columns are equal (or pass a comparison operator to the method):
->whereColumn('squad_user.join_time', '<=', 'seasons.end_time')

Categories