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).
Related
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
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();
?>
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');
I like to know how do i use select not in as a subquery in phalcon
for example i know i can use following to do the notIn with a array values.
return User::query()
->where(" gender!=:gender: ", array('gender' => $gender))
->andWhere(" verify=1 ")
->notInWhere('user_id', "SELECT user_id FROM user_bannned WHERE user_id=:user_id:" )
->order(" last_visit DESC ")
->limit($limit)
->execute();
Problem is
"SELECT user_id FROM user_bannned WHERE user_id=:user_id:"
how do i do this
subquery with model query manager ?
ANY ideas ? or workarounds ?
What exactly is your problem ?
Just do the same:
$this->modelsManager->createBuilder()
->from(['User'=>'User Namespace'])
->where("gender != :gender:,array('gender'=>$gender))
->andWhere("verify=1")
->notInWhere('user_id', "SELECT user_id FROM user_banned WHERE user_id = :user_id:")
->order("last_visit DESC")
->limit($limit)
->getQuery()
->execute();
Thats it.
unfortunately I created the table with a field name called order.
Is there a way to change the query builder to make sure the field name is encased in the ` (apostrophe's)
My query is as follows:
$select = $this->select();
$select->order('order DESC');
$select->where('order < ?', $row->menu_id);
$select->where('menu_id = ?', $row->menu_id);
The builder creates:
SELECT `menu_items`.*
FROM `menu_items`
WHERE (order < '1')
AND (menu_id = '1')
ORDER BY `order` DESC LIMIT 1
I would like it to create
SELECT `menu_items`.*
FROM `menu_items`
WHERE (`order` < '1')
AND (menu_id = '1')
ORDER BY `order` DESC LIMIT 1
thanks
I'm no expert but according to the docs
No quoting is applied to expressions given to the where() or orWhere() methods. If you have column names that need to be quoted, you must use quoteIdentifier() as you form the string for the condition.
There is an example of using quoteIdentifier() in the section "Adding Expression Columns":
$select = $db->select()
->from(array('p' => 'products'),
array('origin' =>
'(p.' . $db->quoteIdentifier('from') . ' + 10)')
);
So you need to do something like this:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $this->select();
$select->order('order DESC');
$select->where($db->quoteIdentifier('order') . ' < ?', $row->menu_id);
$select->where('menu_id = ?', $row->menu_id);
Note that in the order() method,
column names are quoted as identifiers, unless they contain parentheses or are an object of type Zend_Db_Expr.
so you don't have to do anything special there.