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)
Related
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.
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.
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();
Is there any way to convert following query to laravel query builder?
select `employee_id`
from `otc_employee_qualifications`
where `emp_qualifctn_type` IN ('29','27')
group by `employee_id`
having count(Distinct `emp_qualifctn_type`) = 2
Try as below :
$users = DB::table('otc_employee_qualifications')
->select('employee_id')
->whereIn('emp_qualifctn_type', [27,29])
->groupBy('employee_id')
->having(DB::raw("count(Distinct emp_qualifctn_type)"), '=', 2)
->get();
Answer:
DB::select('employee_id')
->from('otc_employee_qualifications')
->whereIn('emp_qualifctn_type', ('29', '27'))
->groupBy('employee_id')
->having(DB::raw('count(Distinct emp_qualifctn_type)'), '=', 2)
->get();
You can convert SQL query into laravel eloquent query by using bellow website.
This will convert SQL query to laravel eloquent base query
Convert SQL query to Eloquent base query
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();