How to convert this SQL query to Laravel Syntax? - mysql

Here my MySQL query (work in phpMyAdmin) :
SELECT waktu_kerusakan, workcenter, COUNT(workcenter) AS jumlah_repair
FROM repair WHERE year(waktu_kerusakan)='2019' GROUP BY workcenter ,
month(waktu_kerusakan) BETWEEN 1 and 6 Order By jumlah_repair Desc
then, i try in Laravel Syntax like this below (not work) :
$sql = Main::groupBy('workcenter')->select('workcenter', \DB::raw('count(*) as frekuensi'))
->whereYear('waktu_kerusakan', 'like', "%".$tahun."%")
->OrderBy('frekuensi', 'Desc')
->groupBy(\DB::raw("MONTH(waktu_kerusakan)"), [1, 6])
->get();
Please anyone help me to convert the MySQL query to Laravel Syntax. Thank you!

Try this.
$repair = DB::table('repair')
->select('waktu_kerusakan','workcenter', DB::raw('COUNT(workcenter) AS jumlah_repair'))
->whereYear('waktu_kerusakan', $tahun)
->groupBy(DB::raw("MONTH(waktu_kerusakan)"), 'workcenter')
->whereIn(DB::raw('MONTH("waktu_kerusakan")'),[1, 6])
->orderBy('frekuensi', 'DESC')
->get()

Try this query :
$sql = Main::select('workcenter', \DB::raw('count(*) as frekuensi'),\DB::raw('MONTH(waktu_kerusakan) as waktu_kerusakan_month'))
->where('waktu_kerusakan',$tahun)
->whereBetween('waktu_kerusakan_month',[1, 6])
->groupBy('workcenter','waktu_kerusakan_month')
->OrderBy('jumlah_repair', 'Desc')
->get();

Related

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

laravel between two dates query error Syntax error

please help me in my query . I am currently getting query error. I am new in laravel and i don't know how to make my query into laravel query. Here is my query :
$date1 = date("Y-m-d", strtotime($request->datepicker));
$date2 = date("Y-m-d", strtotime($request->datepicker1));
$products = DB::table('shipping_table')
->select('products.product_name', 'products.price', DB::raw('Sum(shipping_products.quantity) AS qtysold'), 'shipping_table.sold_date')
->join('shipping_products','shipping_table.shipping_id', '=', 'shipping_products.shipping_id')
->join('products','products.product_id', '=', 'shipping_products.product_id')
->where(['shipping_table.shipping_status', '=' ,1])
->whereBetween(DB::raw("date(shipping_table.sold_date"),[$date1,$date2])
->groupBy('products.product_name')
->get();
please take a look in whereBetween because i am suspecting if it's the one who has wrong syntax.
Error:
Syntax error or access violation: 1064
Got it! You are missing an ) on your between clause:
$date1 = date("Y-m-d", strtotime($request->datepicker));
$date2 = date("Y-m-d", strtotime($request->datepicker1));
$products = DB::table('shipping_table')
->select('products.product_name', 'products.price', DB::raw('Sum(shipping_products.quantity) AS qtysold'), 'shipping_table.sold_date')
->join('shipping_products','shipping_table.shipping_id', '=', 'shipping_products.shipping_id')
->join('products','products.product_id', '=', 'shipping_products.product_id')
->where('shipping_table.shipping_status',1)
->whereBetween(DB::raw("date(shipping_table.sold_date)"),[$date1,$date2])
->groupBy('products.product_name')
->get();
Try now

Laravel - How to do a specific query with query builder

I'm using Laravel and have a very specific query that I don't know how to implement with query builder.
The query:
SET #c_num=0;
SELECT *, #c_num:=#c_num+1 AS 'COUNT'
FROM table_name
WHERE USERID = 2
ORDER BY id
Thank you
You should be able to do something like:
DB::statement(DB::raw('SET #c_num = 0'));
$result = DB::table('table_name')
->selectRaw("*, #c_num:=#c_num+1 AS 'COUNT'")
->where('userid', 2)
->orderBy('id')
->get();
$data = DB::table('table_name')
->where('userid',2)
->select('table_name.*',DB::raw('(#c_num:=#c_num+1) Count')
->orderBy('id')
->get();
You can try the following
DB::table('table_name')
->selectRaw("*, #c_num:=IF(#c_num, #c_num+1, 1) as 'COUNT'")
->where('user_id', 2)
->orderBy('id');

Dynamic table name in join query alias in Laravel 5

How to alias a table name in Laravel 5?
$data['recent_reviews'] = $reviews_table_name::where('source', 'LIKE', '%YELP%')->orderby('reviews_'.$l_state.'.id', 'desc')
->leftJoin($res_tbl_name, 'reviews_'.$l_state.'.restaurant_id', '=', $res_tbl_name.'.id')
->take(6)
->get();
Actually i need the table name alias like below.
$res_tbl_name AS r
Thanks.
Try as given below:
$data['recent_reviews'] = $reviews_table_name::where('source', 'LIKE', '%YELP%')->orderby('reviews_'.$l_state.'.id', 'desc')
->leftJoin("$res_tbl_name as r", 'reviews_'.$l_state.'.restaurant_id', '=', $res_tbl_name.'.id')
->take(6)
->get();
And then use 'r' wherever you used $res_tbl_name

Laravel Query Builder WHERE NOT IN

I have the following sql query
SELECT * FROM exams WHERE exams.id NOT IN (SELECT examId FROM testresults)
how can I convert it into Laravel query builder format?
Thanks.
You can use whereNotIn with a closure:
$result = DB::table('exams')->whereNotIn('id', function($q){
$q->select('examId')->from('testresults');
})->get();
with Eloquent :
$result = Exams::whereNotIn('id', function($q){
$q->select('examId')->from('testresults');
})->get();