CodeIgniter Subquery in Query Builder - php

Is there a way or can someone translate this to code igniter query builder.
SELECT result.id, result.name, result.added
FROM (SELECT tbl.id, tbl.name, tbl.date_added
FROM table tbl
GROUP BY tbl.id) result
GROUP BY result.date_added
I already have my research(link below) but can't find anything like this(query above).
https://www.codeigniter.com/userguide3/database/query_builder.html
https://arjunphp.com/how-to-write-subqueries-in-codeigniter-active-record/
And yes, this can be done using Stored Procedure but I have another reason why I need to implement this as query builder.

try this one.
// Sub Query
$this->db->select('result.id, result.name, result.added')->from('table tbl');
$subQuery = $this->db->get_compiled_select();
// Main Query
$this->db->select('result.id, result.name, result.added')
->from('table tbl')
->where("id IN ($subQuery)", NULL, FALSE)
->get()
->result();

Related

how to pass a pure sql query to laravel eloquent

This SQL:
SELECT COUNT(*) AS total_see_all_video
from users u
WHERE 7 = (SELECT COUNT(*) FROM lecciones_users lu WHERE lu.uuid = u.uuid)
I tried this code but did not work:
$data = LeccionesUsers::select(
DB::raw('COUNT(*) AS total_ase_vis_videos'),
DB::raw('where 7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
)
->join('users', 'lecciones_users.uuid', '=', 'users.uuid')
->get();
Your issue is that you are not correctly forming your query. You can do ->toSql(); instead of ->get(); and you would see the final SQL (would definitely not be the same as the one you wrote first).
So, you should have this to have the same SQL:
$total_see_all_video = LeccionesUsers::whereRaw('7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
->count();
Please, try my query (and also run ->toSql() to see if you have a correct SQL).
I would still recommend to use relationships and it is very weird to do 7 = query.
You can use
DB::query()->fromSub('Raw sql query here..')
and then can perform actions on this.For the reference you can use the documentation fromSub
You can also look into this convert this where break this query to parts to be used accordingly. You can use this section for the reference purpose:
Laravel-Raw-Expressions
Hope this will help you with the result.

Laravel Query Builder returns no results while generated SQL works perfect

I am actively working on a laravel project and have ran into some issues with the Query Builder. I am trying to avoid using DB::Raw but it is looking like I may need to.
$query = app($this->model());
$query = $query->select(['last_name', 'first_name', 'birthday'])
->distinct()
->leftJoin('enrollments', 'students_meta.uid', '=', 'enrollments.student_uid')
->whereIn('enrollments.type', $types)
->where('enrollments.startdate', '<=', "'{$today}'")
->where(function ($join) use ($today) {
$join->where('enrollments.dropdate', '>=', "'{$today}'")
->orWhereNull('enrollments.dropdate');
});
// todo: add viewBy filter
$query = $query->where('birth_month', '=', Carbon::today()->month);
$query = $query->orderBy('last_name')->orderBy('first_name');
$models = $query->get();
The above query builder generates the following SQL :
SELECT distinct `last_name`, `first_name`, `birthday`
FROM `students_meta`
LEFT JOIN `enrollments` ON `students_meta`.`uid` = `enrollments`.`student_uid`
WHERE `enrollments`.`type` IN ('ACTIVE', 'active')
AND `enrollments`.`startdate` <= '2019-10-29'
AND (`enrollments`.`dropdate` >= '2019-10-29' OR `enrollments`.`dropdate` IS NULL)
AND `birth_month` = 10
ORDER BY `last_name` asc, `first_name` asc;
The generated SQL is perfect based on the old code I'm moving from and produces the expected results. If I move some things around, it seems I can get the query builder to return results, but they're not the correct ones. I've looked at other questions/answers about this kind of problem and tried multiple scenarios of moving the join/changing the where's around, still no luck.
Any suggestions? (other than taking the generated sql and running it in DB::Raw()
$query = $query->orderBy('last_name')->orderBy('first_name')->get();
Your query worked fine but you didn't output it.
You can also use ->get()->toArray(); to retrieve the data in array format
Remove your quotes from around $today. The third (or second, if you eliminate the comparison operator) parameter of the where clause sends the values as a parameter in a prepared statement . So
"'{$today}'"
would look like this in a straight query:
where enrollments.startdate <= "'2019-10-29'"
So change your query to
->where('enrollments.startdate', '<=', $today)
Make sure you remove the quotes from all instances like this in your query.

Laravel Query Builder WHERE NOT IN with multiple WHERE clause

I have following query,
SELECT * FROM `users` WHERE approved='1'
and users.id NOT IN (SELECT donations.user_id FROM donations where month='1'
and year='2016');
I have followed Laravel Query Builder WHERE NOT IN
and converted my query like this,
$users = DB::table('users')->where('approved','=',1)->whereNotIn('id', function($q){
$q->select('user_id')->from('donations')->where('month','=','$month')->where('year','=','$year');
})->get();
But its not working, can anybody help me out where i am making mistake.
how can I convert it into Laravel query builder format?
Thanks.
You shouldn't put your $month and $year variables in quotes.
Replace
->where('month','=','$month')->where('year','=','$year')
with
->where('month','=',$month)->where('year','=',$year)

SQL exists in Laravel 5 query builder

Good morning,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models.
This is how the query looks like untranslated:
$anketa = DB::select( DB::raw("SELECT *
FROM v_anketa a
WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
Order by redni_broj limit 1"
), array( 'lv_id_user' => $id_user,
));
I have tried this, but it gives a syntax error near the inner from in the subquery:
$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
)->orderBy('redni_broj')->take(1)->first();
The problem is this exists and a subquery in it. I couldn't find anything regarding this special case.
Assume each table has an appropriate Eloquent model.
V_anketa is a view. The db is postgresql.
As far as the query goes I believe this should work:
$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
$query->select(DB::raw(1))
->from('user_poeni')
->where('anketa.id', '=', 'a.id')
->where('user_id', '=', $id_user);
})
->orderBy('redni_broj')
->first();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view...
Assuming the SQL query is correct, this should work:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent.

Yii2 SQL query grouping OR with AND

Good day.
I am relatively new to yii2.
What am I trying is this sort of SQL query:
SELECT * FROM table WHERE a=1 AND (b=1 OR b=2)
How do I write such query via yii2 query builder?
You need to use orWhere() , andWhere() and where() functions.
the "or" and "and" words are the type of union it made with all the previous where conditions
so, this query:
Table::find()->where('b=1')->orWhere('b=2')->andWhere('a=1')->all();
Make something like this:
select * from Table where (((b=1) or b=2) and a=1)
The all() function tell yii2 to select al records its founds
Note: this code dont work, its just and example.
This can be done like this:
$model = User::find()
->where('a = :a', [':a' => 1])
->andWhere('b = :b1 or b = :b2', [':b1' => 1, ':b2'=> 2])
->all();

Categories