laravel complex query building with join and groupBy - php

I am new to laravel and have the following query in core PHP that needs to be laravel query.
$query="select distinct(c.c_id), 1 'companyToken',c.companyname,u.email,creation_date,CONCAT(eu.firstname,' ',eu.lastname) 'Name' , group_concat(pk.package_name) 'Package Name/Service' , c.notes 'Notes' , c.demo_status 'Demo Status' from ee_company c
left join et_company_payment_methods cpm on cpm.c_id=c.c_id
left join et_packages pk on cpm.package_id = pk.id
inner join (SELECT *
FROM `ee_users`
WHERE c_id IS NOT NULL
GROUP BY c_id) u on u.c_id=c.c_id
left join ee_users eu on eu.id=c.referred_by_user_id
group by c.c_id";
i am just getting started with laravel so finding it difficult to convert such a complex query.
the existing system works fine with this query.
i tried building it with laravel.
$company = DB::table('ee_company')
->leftJoin('et_company_payment_methods', 'ee_company.c_id' , '=', 'et_company_payment_methods.c_id')
->leftJoin('et_packages', 'et_packages.id', '=', 'et_company_payment_methods.package_id')
->join('ee_users',function($join){
$join->on('ee_company.c_id', '=', 'ee_users.c_id')
->whereNotNull('ee_users.c_id')
->groupBy('ee_users.c_id');
})
->leftJoin('ee_users', 'ee_users.id', '=', 'ee_company.referred_by_user_id')
->groupBy('ee_company.c_id');
it gives me following error
Call to undefined method Illuminate\Database\Query\JoinClause::groupBy()

Try this one
$company = DB::table('ee_company')
->leftJoin('et_company_payment_methods', 'ee_company.c_id' , '=', 'et_company_payment_methods.c_id')
->leftJoin('et_packages', 'et_packages.id', '=','et_company_payment_methods.package_id')
->join(DB::raw('SELECT *
FROM `ee_users`
WHERE c_id IS NOT NULL
GROUP BY c_id'),function($join){
$join->on('u.c_id', '=', 'c.c_id');
})
->leftJoin('ee_users', 'ee_users.id', '=', 'ee_company.referred_by_user_id')
->groupBy('ee_company.c_id');

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

Laravel 7: getting rows between two dates where the column is datetime

I'm having trouble building an eloquent query wherein I can recreate this sql command:
The date_created column is datetime.
SELECT * FROM covidchecklist cc
LEFT JOIN patient_appointment pa ON cc.appointment_id = pa.appointment_id
LEFT JOIN users pat ON pa.user_id = pat.id
WHERE DATE_FORMAT(cc.date_created,'%Y-%m-%d') BETWEEN '2021-01-27' AND '2021-01-27'
What I have right now:
CovidChecklist::
leftJoin('patient_appointment', 'covidchecklist.appointment_id', '=', 'patient_appointment.appointment_id')
->leftJoin('users as patient', 'patient_appointment.user_id', '=', 'patient.id')
->whereRaw(' DATE_FORMAT(covidchecklist.date_created,"%Y-%m-%d") BETWEEN '.'$this->date_from'.' AND '.'$this->date_to'.' ')
->select(
*select stuff*
)
->get();
I am using whereRaw since I can't get this to work:
->whereBetween('covidchecklist.date_created', [$this->date_from, $this->date_to])
Try this, mate
->whereBetween(\DB::raw('DATE_FORMAT(covidchecklist.date_created,"%Y-%m-%d")'), [$this->date_from, $this->date_to])

Left join 2 times raw query laravel doesn't work (Laravel)

I tried my raw query sql in laravel and i need to left join it 2 times but the print out is wrong. It different from mysql. I've tried in mysql and it works well
this is my code :
$tabel = DB::SELECT(DB::RAW("
SELECT codeh.info_code kh_infocode, codep.no_code khp_nocode,
codep.info_code khp_infocode,
codep.name_code khp_namecode, t.* FROM transactions t
LEFT JOIN users u ON t.user_id=u.id
LEFT JOIN divisions d ON d.id=u.division_id
LEFT JOIN all_codes codep ON t.code_p_id=codep.id
LEFT JOIN all_codes codeh ON t.allcode_id=codeh.id
WHERE 1=1
AND d.id=$div_id
AND codep.no_code LIKE '$allcode->no_code%'
$db_date
ORDER BY t.date, khp_nocode
"));
it works really well in sql but when i put it in laravel kh_infocode change and the value same like khp_infocode even though kh_infocode has different value with khp_infocode
Everything is in the official docs. It's not even long, go give it a read.
DB::table('transactions as t')
->select(
'codeh.info_code',
'kh_infocode',
'codep.no_code',
'khp_nocode',
'codep.info_code',
'khp_infocode',
'codep.name_code',
'khp_namecode',
't.*',
)
->leftJoin('users as u', 't.user_id', '=', 'u.id')
->leftJoin('all_codes as codep', 't.code_p_id', '=', 'codep.id')
->leftJoin('all_codes as codeh', 't.allcode_id', '=', 'codeh.id')
->where('d.id', '=', $div_id)
->where('codep.no_code', 'like', $allcode->no_code.'%')
->orderBy('t.date')
->orderBy('khp_nocode')
->get();
simply set SQL string directly without DB::RAW()
$tabel = DB::SELECT('your select statment');

Convert SQL to Eloquent to Join multiple table and Count

I have been this SQL working fine, but trying to convert it to Eloquent format, it keeps returning a wrong, SQL entirely which flags error.
Coding with Laravel 5.5
Select arm_articles.article_topic, arm_articles.id, arm_articles.article_id,
COUNT(arm_article_views.view_article_id) AS TotalViews,
COUNT( arm_article_likes.liked_article_id) AS TotalLikes,
COUNT( arm_article_comments.comment_article_id) AS TotalComments
FROM arm_articles
LEFT JOIN arm_article_views ON arm_articles.article_id = arm_article_views.view_article_id
LEFT JOIN arm_article_likes ON arm_articles.article_id = arm_article_likes.liked_article_id
LEFT JOIN arm_article_comments ON arm_articles.article_id = arm_article_comments.comment_article_id
GROUP BY arm_articles.article_id
ORDER BY TotalLikes, TotalLikes, TotalComments ASC`
HOW I MADE ELOQUENT QUERY BUILDER Not working though:
return Datatables::of(PostModel::leftJoin('arm_article_views', 'arm_article_views.view_article_id', '=', 'arm_articles.article_id')
->leftJoin('arm_article_likes','arm_article_likes.liked_article_id', '=', 'arm_articles.article_id')
->leftJoin('arm_article_comments', 'arm_article_comments.comment_article_id','=','arm_articles.article_id')
->selectRaw(
'arm_articles.*,
count(arm_article_views.view_article_id) AS ViewCount'
)
->groupBy('arm_articles.article_id')->orderBy('ViewCount','DESC')
->where('arm_articles.article_contributor_id','=',$contributor_id)
->getQuery())->make(true);
Any hint would be appreciated
Try with this:
DB::table('arm_articles')
->leftJoin('arm_article_views', 'arm_articles.article_id', '=', 'arm_article_views.view_article_id')
->leftJoin('arm_article_likes', 'arm_articles.article_id', '=', 'arm_article_likes.liked_article_id')
->leftJoin('arm_article_comments', 'arm_articles.article_id', '=', 'arm_article_comments.comment_article_id')
->groupBy('arm_articles.article_id', 'article_topic')
->select(
DB::raw('count(arm_article_views.view_article_id) as TotalViews'),
DB::raw('count(arm_article_likes.liked_article_id) as TotalLikes'),
DB::raw('count(arm_article_comments.comment_article_id) as TotalComments'),
'arm_articles.article_id',
'article_topic'
)->get();

Laravel: MYSQL query in laravel

I have a working query goes like this
SELECT s.name as status, q.name as quality, p.name process, count(*)
FROM plates
JOIN equipment_status_codes s on equipment_status_code_id = s.id
JOIN plate_qualities q on plate_quality_id = q.id
JOIN processes p on process_id = p.id WHERE project_id in
(SELECT id
from projects
WHERE name like 'SPIRIT')
GROUP BY s.name, q.name, p.name ASC with ROLLUP
This works just and returns results just fine.
Now I am trying to put this in laravel syntax, but having some difficulties.
So I was thinking something along these lines.
return Plate::select('equipment_status_codes.name as Status', 'plate_qualities.name as Quality', 'processes.name as Process')
->join('equipment_status_codes', 'plates.equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plates.plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'plates.process_id', '=', 'processes.id')
->groupBy(DB::raw('equipment_status_code_id WITH ROLLUP'))
...
...
->get();
Would someone help out. Thanks in advance!
Update:
#Govind Samrow
I have tried this query. It works (with couple of small adjustment) But I am not getting the same results as the one I get when I run the sql query.
I included screen shots.
So when I run the sql query.
I get the following results.
When I run the laravel query.
return DB::table('plates')
->join('equipment_status_codes', 'equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'process_id', '=', 'processes.id')
->whereRaw("project_id IN(SELECT id from projects WHERE name like 'SPIRIT')")
->select(DB::raw('equipment_status_codes.name as Status'), DB::raw('IFNULL(plate_qualities.name, NULL) as Quality'), DB::raw('IFNULL(processes.name, NULL) as process'), DB::raw("COUNT(*) as Total" ))
->groupBy(DB::raw('equipment_status_codes.name WITH ROLLUP', 'plate_qualities.name WITH ROLLUP', 'processes.name WITH ROLLUP', 'asc'))
->get();
I get the following.
Almost there, but I am not sure what's going on?! Any ideas?
Try following Query for Joining with where Condition
return Plate::select('equipment_status_codes.name as Status', 'plate_qualities.name as Quality', 'processes.name as Process')
->join('equipment_status_codes', 'plates.equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plates.plate_quality_id', '=', 'plate_qualities.id')
->join('processes', function($join)
{
$join->on('plates.process_id', '=', 'processes.id')
->whereIn('project_id', DB::table('projects')->where('name','LIKE','SPIRIT')->select('id')->get()->toArray());
})
->groupBy(DB::raw('equipment_status_code_id WITH ROLLUP'))
->get();
Hope this will help.
Use whereRaw for sub query in where clause Try this:
DB::table('plates')
->join('equipment_status_codes', 'equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'process_id', '=', 'processes.id')
->whereRaw("project_id IN(SELECT id from projects WHERE name like 'SPIRIT')")
->select('equipment_status_codes.name as status', 'plate_qualities.name as quality', 'q.name as quality', 'processes.name as Process', DB::raw("COUNT(*) as Total"))
->groupBy(DB::raw('equipment_status_codes.name, plate_qualities.name, processes.name ASC with ROLLUP'))->get();
Here is raw sql result of above that got with toSql():
select `equipment_status_codes`.`name` as `status`, `plate_qualities`.`name` as `quality`, `q`.`name` as `quality`,
`processes`.`name` as `Process`, COUNT(*) as Total from `plates`
inner join `equipment_status_codes` on `equipment_status_code_id` = `equipment_status_codes`.`id`
inner join `plate_qualities` on `plate_quality_id` = `plate_qualities`.`id`
inner join `processes` on `process_id` = `processes`.`id`
where project_id IN(SELECT id from projects WHERE name like 'SPIRIT')
group by equipment_status_codes.name, plate_qualities.name, processes.name ASC with ROLLUP
Note: You can use SQL output with $query->toSql() and then compare with your actual SQL query.
You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method:
Check its link and get knowladge for laravel query builder:-
https://laravel.com/docs/5.4/queries

Categories