I need to select records created at current year, with Eloquent
So far, this is the code I'm using. How can I filter the results to retrieve only the ones created in the current year?
public function vacationsbalance($typeId) {
// Get vacataions balance for existing employee.
$vacationsBalance = $this->vacations()->where('vacation_type_id', '=', $typeId)->sum('days_num');
return $vacationsBalance;
}
Assuming you have timestamps in your table (that is, you have a created_at column with the record's creation date), you can use:
public function vacationsbalance($typeId) {
// Get vacations balance for existing employee and for the current year.
return $this->vacations()
->where('vacation_type_id', '=', $typeId)
->whereRaw('year(`created_at`) = ?', array(date('Y')))
->sum('days_num');
}
Check Eloquent's documentation and look for whereRaw.
Related
I'm making my first laravel project, using postgres, and I'd like to be able to access all the people with a birthday this month (my people table has a birthdate field that's a date). I can use extract to get these records from the database, like so:
select * from people
where extract (month from birthdate) = 11;
But when I try a few different ways in my controller I get 'unknown column' errors:
$birthday_people = DB::table('people')
->where ("extract(month from birthdate)", "=", "11")
->get();
(I'll ultimately adjust it to compare with Carbon::now()->month, and use the model Person::all(), but until I get some results coming through I'm going as simple as possible)
Is there a special way to get the month from a date in laravel?
Update: I'm using a scope now in my Person model. I can get person results to come through when I give it an exact date:
public function scopeBirthdays($query)
{
return $query->where('birthdate', '=', '1947-11-02');
}
And I can get results back for month if I do it this way, but the catch is it doesn't seem to know it's a collection of People anymore (I can't access person columns when I display it out and I can't chain other scopes):
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', ['11'])->get();
}
Laravel's query builder offers 'whereMonth'- (seems the most right), but it gave me an 'undefined function' error until I put the bool on the end, and now the current error suggests that it's interpretting number of months instead of which one(?):
public function scopeBirthdays($query)
{
return $query->whereMonth('birthdate', '=', Carbon::today()->month, true);
}
I get:
Syntax error: 7 ERROR: syntax error at or near "month"
LINE 1: select * from "people" where 1 month("birthdate") = $1
^ (SQL: select * from "people" where 1 month("birthdate") = 11)
Final update: I was able to get results back (that were correctly interpretted as people) by using whereRaw in my scope:
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', [Carbon::today()->month])->orderBy ('birthdate', 'asc');
}
Thanks, everyone!
based on previous question try:
$birthday_people = DB::table('people')
->whereRaw("extract(month from birthdate)", "=", "11")
->get();
You can set is as relationship
public function custom(){
return $this->hasMany('App\Models\People')->whereRaw("extract(month from birthdate)", "=", "11");
}
You could try something like this. It will return as an instance of App\People so you will be able to use your eloquent functions still.
public function scopeBirthdays($query)
{
return $query->where('birthdate', 'LIKE', Carbon::today()->year . '-'.Carbon::today()->month.'%');
}
I don't have much experience with Carbon, I'm assuming that Carbon::today() will return an object with the year, month, and date.
I currently use GF for reservations 'Arrive' and 'Departure'. I would like the date displayed on the 'Departure' to always be one date ahead of the 'Arrival' date, regards of what date the guest picks. Then can pick a custom 'Departure' date, but as a default I'd like to show one date forward of the 'Arrival' date no matter what 'Arrival' date they choose.
This is possible with the gform_datepicker_options_pre_init JS filter. Example #3 is what you're after:
gform.addFilter( 'gform_datepicker_options_pre_init', function( optionsObj, formId, fieldId ) {
if ( formId == 12 && fieldId == 8 ) {
optionsObj.minDate = 0;
optionsObj.onClose = function (dateText, inst) {
jQuery('#input_12_9').datepicker('option', 'minDate', dateText).datepicker('setDate', dateText);
};
}
return optionsObj;
});
If you're looking for a code-less solution, I've written a plugin that let's you do this in just a few clicks called GP Limit Dates.
Also, here is an article that addresses your specific need: How to restrict dates in second date field based on date selected in first date field with Gravity Forms
I am working in Yii framework. I am having Poll table with fields as-
-pollId
-pollQuestion
-Isactive
-publishDate
-isPublish
when new poll is created,that date get inserted into publishDate field.
e.g.2012-04-04 02:23:45 In this format entry get inserted.
Now i want to check weather this publishDate is smaller than today's date or current date. i.e.publishDate should not be greater than current date.
So how to check this in yii? Please help me
As per normal PHP. Assuming $model is the submitted form and you have assigned (after the form has been submitted) $model->attributes = $_POST['MyModel']
You can then use:
if ($model->publishDate < date('Y-m-d H:i:s')){
// it is smaller
}
Another thing you could look at is using Yii's model validation. You could store the created date (which would be todays date) and then compare that to the publishDate in the form submit:
$model->created = date("Y-m-d H:i:s");
if ($model->validate){
...
}
And in your Poll model:
array('publishDate ','compare','created','operator'=>'<', 'message'=>'Publish Date must be smaller than the current date'),
I use Magento 1.7.0.2.
I'd like to show the 8 latest added products in my homepage, but without setting a date "from" and "to". I need it to be automatically.
Does anyone know of a solution?
Product IDs are incremental. By ordering them descending and limiting the collection to 8 you will have 8 last products.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order('entity_id desc')->limit(8);
/* just for testing
Mage::log($collection->getSelect()->assemble());
foreach ($collection as $product) {
Mage::log($product->getSku());
} */
With the collection you can do whatever you need, add visibility and status filter etc.
in order to do that you will need to use the date that the order was created. The key to display all products information as price, name, and etc. is to us ->addAttributeToSelect('*') Here is the script:
$store_id = Mage::app()->getStore()->getId();
$_products = Mage::getResourceModel('reports/product_collection')
->addStoreFilter($store_id)
->addAttributeToFilter('visibility', 4)
->addAttributeToFilter('status', 1)
->addAttributeToSelect('*')
->setVisibility(array(2,3,4))
->setOrder('created_at', 'desc')
->setPage(1, 9);
I have a postgresql table with data connected to dates. Each row has data and a date, for example:
2011-02-03 JOHN Male etc
I am using playframework. i have created a model named student.java.
and in application.java i have done something like this where firstDate and lastdate are given by user,
List (student studentList) = student.find("timestamp BETWEEN 'firstDate' and 'lastDate'").fetch();
i want to fetch all the data present between those two dates.
But i know the query is not correct. Please help me out.
Thanks in advance. :)
public static final List<Student> findWithDates(Date firstDate, Date lastDate) {
return find("from Student student where student.date >= ? and student.date <=?",
firstDate, lastDate).fetch();
}