Translate a MySql query in a Laravel query builder - mysql

SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC
how can I Translate this MySql query in a Laravel query builder ?

Check Laravel docs on query builder and see the examples, you can easily convert your SQL to query builder:
use Illuminate\Support\Facades\DB;
DB::table('views')
->selectRaw("apartment_id, COUNT(created_at) AS n_view, DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
->where('apartment_id', '=', 36)
->groupBy('day_view')
->orderByRaw('COUNT(created_at) DESC')
->get();

You can do like that use App\Views; use DB;
Views::select('apartment_id', DB::raw("COUNT(created_at) as n_view") ,DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view"))->where('apartment_id' ,36)->orderBy('n_view', 'desc')->get();

$data = $this->views;
$data = $data->select(
"apartment_id",
DB::raw("COUNT(created_at) AS n_view"),
DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
);
$data = $data->where("apartment_id", 36);
$data = $data->groupBy("day_view");
$data = $data->orderBy("created_at", "desc");
$data = $data->get();

DB::table('views')
->selectRaw("apartment_id, COUNT(created_at) AS n_view, DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
->where("apartment_id", "=", "36")
->groupBy('day_view')
->orderBy(n_view, "DESC")
->get();

Related

Sub Query on Query Builder on Laravel

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

MySQL query with DATE_FORMAT() to Laravel Querybuilder (or Eloquent)

I'm trying to get records from a table on a specific day.
Dates's format: datetime (YYYY-MM-DD HH:II:SS)
I'm trying to translate a MySQL query to Laravel query builder. But I don't know how to deal with the DATE_FORMAT().
Here is MySQL query
SELECT * FROM events
JOIN customers ON events.id_customer = customers.id
WHERE start_date > DATE_FORMAT("2017-06-15", "%Y-%m-%d %H:%i:%s")
AND end_date < DATE_FORMAT("2017-06-16", "%Y-%m-%d %H:%i:%s")
;
In my controller I get a date (string) that I put into a DateTime
$date_datetime = new \DateTime(Input::get('date_string'));
And then change its format
$query_date = date_format($date_datetime, 'Y-m-d H:i:s');
I've tried the following code, but it is obviously not working
$pdf_events = DB::table('events')
->join('customers', 'events.id_customer', '=', 'customers.id')
->select(...)
->whereRaw("start_date > DATE_FORMAT($query_date, '%Y-%m-%d %H:%i:%s')")
->whereRaw("end_date < DATE_FORMAT($query_date, '%Y-%m-%d %H:%i:%s')+1")
->get();
I strongly recommend using Carbon for handling DateTime in Laravel since it has support out of the box.
Now, how to use it to resolve your problem?
First, you need to convert your input into Carbon object.
$start_date = Carbon::parse(Input::get('date_string'));
// Assuming you want the end date 1 day later at same time
$end_date = $start_date->addDay();
// You could change the format with format() but in this case we don't need to
Then in your Eloquent, you can use the Carbon Datetime object to query using where()
$pdf_events = DB::table('events')
->join('customers', 'events.id_customer', '=', 'customers.id')
->select(...)
->where("start_date", ">", $start_date)
->where("end_date", "<", $end_date)
->get();
You can pass Carbon (doc) objects to compare dates. For example:
->where('start_date', '=', Carbon::now())
You can build a custom Carbon object for a custom date-time to pass into the where clause.
You don't need DATE_FORMAT, Try this:
$query_start_date = \Carbon\Carbon::createFromFormat("Y-m-d H:i:s", request()->date_string);
// Add 1 day to the date
$query_end_date = $query_start_date->addDay();
$pdf_events = DB::table('events')
->join('customers', 'events.id_customer', '=', 'customers.id')
->where(
[
["start_date", ">", $query_start_date],
["end_date", "<", $query_end_date]
]
)->get();
use Datetime;
$end_date1 = $request->input('end_date');
$EndDateTime = DateTime::createFromFormat('d/m/Y H:i:s', $end_date1);
$end_date = $EndDateTime->format('Y-m-d H:i:s');
try like this its work for me

MySQL date in between month and year

How to query date month and year between from_date and to_date?
What I tired:
$posts = my_table::whereYear('from_date', '>=', $year)
->whereMonth('from_date', '>=', $month)
->whereYear('to_date', '<=', $year)
->whereMonth('to_date', '<=', $month)
->get();
Query I want to execute:
SELECT * FROM my_table
WHERE (MONTH(from_date)>=2 AND (Year(from_date)>=2019)
AND (MONTH(to_date)=<4 AND (Year(to_date)=<2019)
I think this is what you might be looking for:
$posts = my_table::whereRaw("(MONTH('from_date') > 2 AND YEAR('from_date') >= 2019)")
->whereRaw("(MONTH('to_date') < 4 AND YEAR('to_date') <= 2019)")
->get();
Here's an example.
You can use the eloquent method too.
$result = my_table::where(function($query){
$query->where(DB::raw('MONTH(from_date)'), '>=' , 2)
->where(DB::raw('Year(from_date)'), '>=' , 2019);
})
->where(function($query){
$query->where(DB::raw('MONTH(to_date)'), '<=' , 4)
->where(DB::raw('YEAR(to_date)'), '<=' , 2019);
})
->get();
you may also do it in this way.
return Post::whereRaw("STR_TO_DATE('from_date', '%M%Y') > STR_TO_DATE('022019', '%M%Y')")
->whereRaw("STR_TO_DATE('from_date', '%M%Y') < STR_TO_DATE('042019', '%M%Y')")
->get();

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

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