Laravel - How to do a specific query with query builder - mysql

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

Related

How to convert this SQL query to Laravel Syntax?

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

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

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

SQL query with count and group by in Symfony2 QueryBuilder

I need your help please. I have this SQL query :
SELECT * , COUNT( * ) AS count FROM mytable GROUP BY email ORDER BY id DESC LIMIT 0 , 30
But I would like to do this in Symfony2 with Doctrine and the createQueryBuilder().
I try this, but didn't work :
$db = $this->createQueryBuilder('s');
$db->andWhere('COUNT( * ) AS count');
$db->groupBy('s.email');
$db->orderBy('s.id', 'DESC');
Can you help me please ? Thanks :)
You need to run 2 queries:
$db = $this->createQueryBuilder();
$db
->select('s')
->groupBy('s.email')
->orderBy('s.id', 'DESC')
->setMaxResults(30);
$qb->getQuery()->getResult();
and
$db = $this->createQueryBuilder();
$db
->select('count(s)')
->groupBy('s.email')
//->orderBy('s.id', 'DESC')
->setMaxResults(1);
$qb->getQuery()->getSingleScalarResult();
I tried to use
$query->select('COUNT(DISTINCT u)');
and it's seem to work fine so far.
$db = $this->createQueryBuilder('mytable');
$db
->addSelect('COUNT(*) as count')
->groupBy('mytable.email')
->orderBy('mytable.id', 'DESC')
->setFirstResult(0)
->setMaxResults(30);
$result = $db->getQuery()->getResult();
Hope it helps even if it's an old stack

Zend DB Select : ORDER BY FIELD('id',some_array) - how?

How would you write the following query in Zend framework?
SELECT * FROM table_name ORDER BY FIELD(field_name, 'Small','Medium','Large');
I just need the "Order by" part :)
Thanks!
What about this:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('table_name')
->order(new Zend_Db_Expr("FIELD(field_name, 'Small','Medium','Large')"));
var_dump($select->assemble());
Results in:
string 'SELECT `table_name`.* FROM `table_name` ORDER BY FIELD(field_name, 'Small','Medium','Large')' (length=92)
$select->order(new Zend_Db_Expr('FIELD(field_name, 'Small','Medium','Large')'));
I think you should do:
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from(table_name)
->order(new Zend_Db_Expr("FIELD(field_name, 'Small','Medium','Large')")));