Sub Query on Query Builder on Laravel - mysql

I want to make query builder with this query, but it won't work.
SELECT
karyawan.id,
karyawan.nama_lengkap,
departemen.nama,
jabatan.nama,
(
SELECT
tingkat
FROM
riwayat_pendidikan
WHERE
karyawan_id = karyawan.id
ORDER BY
tahun_selesai DESC
LIMIT
1
) AS pendidikan_terakhir
FROM
karyawan
INNER JOIN jabatan ON karyawan.jabatan_id = jabatan.id
INNER JOIN departemen ON jabatan.departemen_id = departemen.id;
Well its done using this Query Builder , Thanks guys i'm using this https://sql-to-laravel-builder.herokuapp.com/
DB::table('karyawan')
->select('karyawan.id as id','karyawan.nama_lengkap as nama','departemen.nama as departemen'
,'jabatan.nama as jabatan','karyawan.jenis_kelamin','karyawan.nomor_hp_whatsapp','karyawan.status_pegawai',
'karyawan.tanggal_mulai_bekerja','karyawan.tanggal_keluar_bekerja','karyawan.tanggal_akhir_kontrak',
'karyawan.telepon_rumah','karyawan.telepon_kantor',
DB::raw('(SELECT CONCAT(riwayat_pendidikan.tingkat," ", riwayat_pendidikan.jurusan)
AS FIRSTNAME FROM riwayat_pendidikan WHERE karyawan_id = karyawan.id ORDER BY
tahun_selesai DESC LIMIT 1 ) AS pendidikan_terakhir'))
->join('jabatan','karyawan.jabatan_id','=','jabatan.id')
->join('departemen','jabatan.departemen_id','=','departemen.id')
->where('departemen.nama','=','Staff')
->get();

use Illuminate\Support\Facades\DB;
DB::table('karyawan')
->join('jabatan', 'jabatan.id', '=', 'karyawan.jabatan_id')
->join('departemen', 'departemen.id', '=', 'jabatan.departemen_id')
->select([
'karyawan.id',
'karyawan.nama_lengkap',
'departemen.nama',
'jabatan.nama',
])
->addSelect([
'pendidikan_terakhir' => DB::table('riwayat_pendidikan')
->select('tingkat')
->whereColumn('riwayat_pendidikan.karyawan_id', 'karyawan.id')
->orderByDesc('tahun_selesai')
->limit(1)
])->get();
Documentation

Related

Laravel (v6.x) addSelect() always returns a null value for the subquery field

I have this Eloquent query:
$users = User::query()
->addSelect([
'latest_login' => Login::select('login_time')
->where('logins.user_id', 'users.id')
->latest('login_time')
->take(1)
])
->orderBy('latest_login', 'DESC')
->get();
The problem is that the `latest_login' field is always null.
However if I run the query in mysql the field is fully populated:
'SELECT `users`.*, (SELECT `login_time` FROM `logins` WHERE `user_id` = users.id AND `login_time` IS NOT NULL ORDER BY `login_time` DESC LIMIT 1) AS `last_login` FROM `users` WHERE `logged_in` > 0 ORDER BY `last_login` DESC
I have also tried running the raw query in Laravel using DB::select() and that also returns null for the field.
Any ideas please?
I might be wrong here but I think you have to use whereColumn instead of where
to actually use the value of the column and not just a string with the column's name.
$users = User::query()
->addSelect([
'latest_login' => Login::select('login_time')
->whereColumn('logins.user_id', 'users.id')
->latest('login_time')
->take(1)
])
->orderBy('latest_login', 'DESC')
->get();

Laravel's Database Query Builder

I am trying to write a MySQL select query using Laravel's Database Query Builder
I have this mysql query:
SELECT * FROM `tweets` WHERE `user_id` = 1 OR `user_id` in (SELECT `follows_id` from `follows` where `user_id` = 1)
I am trying to write it for Laravel
$users = DB::table('tweets')
->where('user_id', '=', 1)
how can this be done?
You can do something like this even though it looks ugly.
$tweets = DB::table('tweets')
->where('user_id', 1)
->orWhereIn('user_id', DB::table('follows')->select('follows_id')->where('user_id', 1)->pluck('follows_id'))
->get();
I would suggest a SQL rewrite as OR and IN(SELECT ...) tends to optimize badly.
The SQL result might be wrong as you didn't provide example data and expected result see Why should I provide a Minimal Reproducible Example for a very simple SQL query? for providing those.
SELECT
tweets.*
FROM
tweets
WHERE
tweets.user_id = 1
UNION ALL
SELECT
tweets.*
FROM
tweets
INNER JOIN
follows ON tweets.user_id = follows.follows_id
WHERE
follows.user_id = 1
I believe the following Laraval code should do that. But not sure as i didn't program in Laravel for some time now.
<?php
$first = DB::table('tweets')
->select('tweets.*')
->where('user_id', '=', 1);
$second = DB::table('tweets')
->select('tweets.*')
->join('follows', 'tweets.user_id', '=', 'follows.follows_id')
->where('follows.user_id ', '=', 1)
->union($first)
->get();
?>

Convert Raw SQL query to Laravel DB Query

I have the following raw SQL query:
select a.id user_id, a.email_address, a.name_first, a.name_last, count(b.id) number_of_videos, sum(b.vimeo_duration) total_duration, sum(b.count_watched) total_playbacks
from users a,
videos b
where a.id = b.tutor_id
and a.email_address in ('candace_rennie#yahoo.com', 'tjm#hiltoncollege.com', 'matthewjameshenshall#gmail.com', 'nkululeko#syafunda.co.za', 'khulile#syafunda.co.za', 'nzakheni#syafunda.co.za')
group by a.id;
This correctly gets 6 rows from the database. I'm trying to convert this to a Laravel database query like so:
$totals = DB::table('users')
->select(DB::Raw('users.id as user_id'), 'users.email_address', 'users.name_first', 'users.name_last', DB::Raw('count(videos.id) as number_of_videos'), DB::Raw('sum(videos.vimeo_duration) as total_duration'), DB::Raw('sum(videos.count_watched) as total_playbacks'))
->join('videos', 'users.id', '=', 'videos.tutor_id')
->where('users.id', 'videos.tutor_id')
->whereIn('users.email_address', array('candace_rennie#yahoo.com', 'tjm#hiltoncollege.com', 'matthewjameshenshall#gmail.com', 'nkululeko#syafunda.co.za', 'khulile#syafunda.co.za', 'nzakheni#syafunda.co.za'))
->groupBy('users.id')
->get();
This however return 0 rows. Is there anything I'm missing?
It should be smth like below even tho groupBy user id does not help much as id is unique.
$aggregates = [
DB::raw('count(b.id) as number_of_videos'),
DB::raw('sum(b.vimeo_duration) as total_duration'),
DB::raw('sum(b.count_watched) as total_playbacks'),
];
$simpleSelects = ['users.email_address', users.id, 'users.name_first', 'users.name_last'];
$emails = ['candace_rennie#yahoo.com', 'tjm#hiltoncollege.com'....]
$users = Users::select(array_merge($simpleSelects, $aggregates))
->leftJoin('videos as b', function ($join) use ($emails) {
$join->on('b.tutor_id', 'a.id')
->whereIn('users.email_address', $emails);
})
->groupBy('users.id')
->get();
Try to remove this line:
->where('users.id', 'videos.tutor_id')
List item
after sql code convert into laravel
DB::select('posts.id','posts.title','posts.body')
->from('posts')
->where('posts.author_id', '=', 1)
->orderBy('posts.published_at', 'DESC')
->limit(10)
->get();

How I Can Convert SQL query to Query Builder

How can I convert the following query into a laravel eloquent query?
SELECT demand_costings.pr_number as Demand_Costing,work_types.work_types,
SUM(demand_costings.pr_quantity_in_pcs) as Total
FROM demand_costings
INNER JOIN work_types
ON demand_costings.worktype_id=work_types.id
GROUP BY work_types.work_types;
You can use laravel's DB facade:
$data = DB::table('table_name')
->select(DB::raw('emand_costings.pr_number as Demand_Costing,work_types.work_types,SUM(demand_costings.pr_quantity_in_pcs) as Total FROM demand_costings INNER JOIN work_types ON demand_costings.worktype_id=work_types.id'))
->groupBy('work_types')
->get();
Try this:
DB::table('demand_costings')
->select([
'pr_number as Demand_Costing',
'work_types',
'SUM(pr_quantity_in_pcs) as Total'
])
->join('work_types', 'demand_costings.worktype_id', '=', 'work_types.id')
->groupBy('work_types.work_types')
->get();

how to convert this simple sql query to doctrine querybuilder

I'm using php doctrine, and i can't convert this sql query to querybuilder .
i have problems with "group by"
any help please ?
SELECT * FROM message WHERE sender_id='2' OR receiver_id = '2' Group By (if(sender_id > receiver_id, sender_id, receiver_id)) , (if(sender_id <= receiver_id, sender_id,receiver_id)) Order BY createdAt DESC
this is what i did but i need condition on groupby
$queryBuilder = $this->createQueryBuilder('m');
$queryBuilder->where('m.sender = :user or m.receiver =:user')
->groupBy('m.sender','m.receiver')
->orderBy('m.createdAt', 'Desc')
->setParameter('user', $user);
This should probably work:
$qb = $this->createQueryBuilder('m');
$qb->where($qb->expr()->orX(
$qb->expr()->eq('m.sender', ':user'),
$qb->expr()->eq('m.receiver', ':user')
))->groupBy('m.sender')
->addGroupBy('m.receiver')
->orderBy('m.createdAt', 'DESC')
->setParameter('user', $user);
So apart from factoring out your where statement into relevant expr() statements (documentation) the only other change is splitting your groupBy into groupBy and then addGroupBy. You can do the same if you ever need to order by more than one things (orderBy and addOrderBy).