MySQL YEAR() equivalent in Laravel query builder - php

With MySQL, I can use the YEAR() function like this to filter by the year of a date field in a WHERE clause:
SELECT noworkorder FROM workorders WHERE YEAR(date)=2015;
In Laravel, I can of course achieve the same thing with a raw expression:
$data = DB::table('workorders')
->select('noworkorder')
->where(DB::raw('YEAR(date)=2015'))
->orderby('noworkorder', 'desc')
->get();
But is there a way to do this without raw expressions?

The query builder has a whereYear method:
$data = DB::table('workorders')
->select('noworkorder')
->whereYear('date', '=', 2015)
->orderby('noworkorder', 'desc')
->get();

Related

How to use now() with Eloquent?

What the best way to use now() with Eloquent? I mean, is there a native Eloquent function to return today's date? I'm using Slim framework and for this query, the only solution that I found is:
$now = date('Y/m/d H:i:s', time());
$articles = Article::where('created_at', '<', $now)
->orderBy('created_at', 'DESC')
->limit(10)
->get();
It's a bit messy, isn't it?
I could use Carbon but it would make an extra dependency...
Thanks
You have two options here: either use DB::raw method to make where method process the given expression as is:
$articles = Article::where(DB::raw('created_at < NOW()'))
->orderBy('created_at', 'DESC')
->limit(10)
->get();
... or use whereRaw method:
$articles = Article::whereRaw('created_at < NOW()')
->orderBy('created_at', 'DESC')
->limit(10)
->get();
As a sidenote, Eloquent has several helper methods for datetime-related processing - whereDate, whereMonth, whereDay, whereYear and whereTime. I'm really not sure those can be used in this specific case, but they might turn helpful elsewhere.

Laravel Model Using Or in where Condition?

I want to get the template from user_webhook table in my database.In WHERE condition i am checking user_id,app_id and if either notify_admin or notify_customer value is 1 in user_webhook table.I am using query..
$templates= $this->where('notify_admin',1)
->orwhere('notify_customer',1)
->where('user_webhooks.user_id',$user_id)
->where('user_webhooks.app_id',$app_id)
->select( 'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
'user_webhooks.sms_template as sms'
)
->join ('webhooks',function($join){
$join>on('webhooks.id','=','user_webhooks.webhook_id');
})
->get()
->toArray();
when i get query using DB::getQueryLog(), I found the query seems Like
select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
`telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
`telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
`telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`,
`telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`,
`telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks`
inner join
`telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id`
where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id`
= ? and `telhok_user_webhooks`.`app_id` = ?
The result of query giving result of all app_id and user_id.
So Please tell me use of OR in where condition.
Thanks in advance.
You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
Advanced usage:
Usere::where('id', 46)
->where('id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
The whereIn method verifies that a given column's value is contained within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
More: https://laravel.com/docs/5.5/queries
Change
->where('notify_admin',1)
->orwhere('notify_customer',1)
to
->where(function($q){
$q->where('notify_admin',1)
->orWhere('notify_customer',1);
})
Without this, the orWhere will compare to all other wheres in your query instead of just comparing those two columns

Laravel whereDate() in SELECT Statement

Query
<?php
$vrec = DB::table('st_sales_live_bk')->where('brandid', $brandid)
->where('branchid', $branchid)
->where('module_id', 1)
->select(DB::raw('trunc(EODATE)'))
->get();
return $vrec;
I was using whereDate() in conditions to truncate a DateTime field. Now I want to select a DateTime field (eodate) using DB::raw, if possible. Any help?
You have to use DB::raw before your where conditions. Your query should look like
$vrec=DB::table('st_sales_live_bk')->select(DB::raw('trunc(EODATE)'))
->where('brandid', $brandid)
->where('branchid', $branchid)
->where('module_id', 1)
->get();
return $vrec;

Different values when use DB::raw() in second param on where()

I have next query in Laravel Eloquent:
$buildings = Building::select('buildings.*')->join(
DB::raw('('.
(
IngameBuilding::select('buildings.building_id', 'buildings.level')
->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
->toSql()
).
') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
->where('buildings.level', '>', 'added_buildings.level')
->get();
This query returns all allowed rows from base, but one row more. When I added DB::raw() in where() return values is valid.
Good-working code:
$buildings = Building::select('buildings.*')->join(
DB::raw('('.
(
IngameBuilding::select('buildings.building_id', 'buildings.level')
->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
->toSql()
).
') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
->where('buildings.level', '>', DB::raw('`added_buildings`.`level`'))
->get();
Why first code workig, hmm.. Wrong?
I'm not a big fan of Laravel at all.
I've got only small experience with this framework but i'm almost sure that where function accepts only a 'constant' values to be checked against.
If you'll get an output of this query using toSQL method on the query object you will see that eloquent will convert it as something like:
(...) where buildings.level > 'added_buildings.level'
so the condition checks if the buildings.level (whatever the type is)
is greater than the given string and not the column value.
Using the DB::raw you're getting the proper sql as the eloquent won't parse/convert it.
You would need to use whereRaw method I suppose.
http://laravel.com/docs/4.2/queries#introduction

Using Distinct in Laravel Fluent

I have this join:
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->where('is_published', '=', 1)
But it unsurprisingly returns duplicate records, so I try to use distinct():
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->distinct()
->where('is_published', '=', 1)
but I want to use distinct() on a specific single field which I'd easily be able to do in SQL. It seems distinct() does not take parameters, i.e. I can't say distinct('volunteer.id').
Can anyone point me to how can I remove my duplicate records? I bet this is another forehead slapper for me.
In my project I tried distinct() and groupby() too and both of them worked:
//Distinct version.
Company_Customer_Product::where('Company_id', '=', $companyid)->distinct()->get(array('Customer_id'));
//Goup by version.
Company_Customer_Product::where('Company_id', '=', $companyid)->groupby('Customer_id')->get(array('Customer_id'));
According to this, distinct() should work in your case too, just use it with get():
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->distinct()
->where('is_published', '=', 1)
->get(array('volunteer.id'));
Otherwise you don't need distinct() when you use groupby() so you could just use:
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->group_by('volunteer.id')
->where('is_published', '=', 1)
->get(array('volunteer.id'));

Categories