How to show data with less than current date in yii? - php

How do i filter the date which is less than the current date?
Company::model()->with(array(
'Bundles'=>array(
'condition'=>'Bundles.status=1',
'order'=>'payment_date DESC',
),
))->findByPk($company_id);
Currently above code is displaying all data whose status = 1
but i want to show the data whose expiry_date should be less than current date. How can i achieve this?
This is what i have tried so far but NO success.
Company::model()->with(array(
'Bundles'=>array(
'condition'=>'Bundles.expiry_date < date("Y-m-d H:i:s")',
'order'=>'payment_date DESC'
),
))->findByPk($company_id);

You can try something like this.
Company::model()->with(array(
'Bundles'=>array(
'condition'=>'Bundles.expiry_date < CURDATE()',
'order'=>'payment_date DESC'
),
))->findByPk($company_id);
You cannot put php date function into SQL statement in the way u did it. Try to use CURDATE()

Related

update date to next day in laravel

I want to update my date to next day date. How Can I do it?
Now I do it using this.
$calendar = Calendar::find($id);
$calendar->update(['started_at' => $calendar->started_at->addDay(1)));
or I can do it
$calendar->started_at->addDay(1);
$calendar->save();
But this solutions is bad for me because there are 2 request in database. I wont do it using only one request.
Is there a way to dynamically update date to next day date?
For example
Calendar::where('id', $id)->updateToNextDay('started_at');
I find also sql equivalent
UPDATE `calendar` SET `started_at` = `started_at` - INTERVAL 1 DAY;
Thanks for attention.
Calendar::where('id', $id)->update() is just syntactical sugar. This proxies you to the Query Builder and is the same as running DB::table('calendar')->where('id', $id)->update();
The power of a model in an ORM is obtaining the data from the database, mapping it to properties in an object, and then manipulating that object. The overhead of a single select for an update is pretty small and if you're worried about that overhead in the development phase, you're probably overoptimizing.
If you wish to forego the select, you can use the Query Builder with a raw SQL expression. Either will call the Query Builder and run the same exact query:
Calendar::where('id', $id)
->update(['started_at' => DB::raw("started_at + INTERVAL 1 DAY")]);
or
DB::table('calendars')->where('id', $id)
->update(['started_at' => DB::raw("started_at + INTERVAL 1 DAY")]);
This should work
Calendar::where('id', $id)->update([
'started_at' => DB::raw("DATE_ADD(started_at, INTERVAL 1 DAY)")
]);
Let me know :)
$startDate = date_timestamp_get($calendar->started_at);
$date = date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
$calendar->update(['started_at' => $date]);
You can write your own method in Calendar model like,
public function updateToNextDay(string $column)
{
$this->update([
$column => \Db::raw("$column + INTERVAL DAY 1");
]);
}
Not tested, but it should work.

Sorting a NON-SQL table column in a table containing data from SQL query

Below I have stripped down my code to a simplified version. I am storing SQL SELECT results for:
last name (dlname)
category (category)
date this data was added to database (date_added)
clients name (client)
I have appended an additional field outside the SQL SELECT called 'days_on_list'. This field shows the number of days since the data was added to the database, making the table output 5 columns of user data. ALL 5 COLUMNS ARE TO BE SORTABLE.
I am using server-side JSON and have successfully been able to display this to the table and perform sorting on 4 of the 5 columns. The problem is that I am unable to sort the 'days_on_list' field as the PHP file containing the SQL code only allows me to sort the 4 fields from the select query. Is there a way I can make 'days_on_list' column be sortable in the table? I know I can add this field to the sql table, but I would have to run a scheduled event on the server to update this daily (which I am not comfortable with).
Is there another way to allow for this kind of flexible table sorting?
Sorry about the question title (may be confusing), I was having trouble putting this into a question.
/*SQL CODE ABOVE HERE STORES SELECT RETURNS IN $result*/
$cart = array();
$i = 0; //index the entries
// get variables from sql result.
if ($num_rows > 0) { //if table is populated...
while ($row = mysqli_fetch_assoc($result)) {
//calculate days on list by getting the number of days from
//the 'date_added' to today
$date1 = date_create($row['date_added']);
$today = date_create(date("d-m-Y"));
$interval = date_diff($date1, $today);
$doty = $interval - > format("%a");
$cart[$i] = array(
"dlname" => htmlspecialchars($row['dlname']),
"category" => htmlspecialchars($row['category']),
"date_added" => htmlspecialchars($row['date_added']),
"client" => htmlspecialchars($row['client']),
"days_on_list" => $doty, //date_added to now
);
$i = $i + 1; //add next row
}
//encoding the PHP array
$json_server_pagination_data = array(
"total" => intval($num_rows),
"rows" => $cart, //array data
);
}
echo json_encode($json_server_pagination_data);
Because days_on_list is calculated by simply comparing date_added to the current date, sorting by days_on_list should have exactly the reverse effect as sorting by date_added.
In other words, you don't actually need to sort by days_on_list. If the user selects days_on_list as the sort column, just use ORDER BY date_added (in the opposite direction ASC/DESC).

How to structure database and populate Calendar in CodeIgniter 2 project?

I've searched SO and Google and can't quite find what I need.
I'm building a simple Event Calendar with CodeIgniter 2. As per the CodeIgniter documentation, this is the basic code structure and it's working...
// $data[2] contains the data for day #2, etc.
$data[2] = 'event title 1';
$data[8] = 'event title 2<br/>event title 3';
$data[13] = 'event title';
$data[24] = 'event title';
// {content} in template is where $data is inserted for each day
$prefs = array (
// my calendar options
'template' => '
{cal_cell_content}{day}<br/>{content}{/cal_cell_content}
{cal_cell_content_today}<div class="highlight">{day}<br/>{content}</div>{/cal_cell_content_today}'
);
$this->load->library('calendar', $prefs);
$year = ($year === FALSE ? date('Y') : $year);
$month = ($month === FALSE ? date('m') : $month);
echo $this->calendar->generate($year, $month, $data);
Now comes how I've set up my database table...
Each Event has a title field and that creates the $slug. (~/events/view/title-slug)
Each Event has a date field and the data format is mm/dd/yyyy
Now, I'm thinking about how I'd query the database for a particular month/year and extract the data to insert into each $data[] variable.
It seems like I'll need to do the following:
create new columns in my database table for month, day, and year.
take my date input data, after it's validated, and save it into date column.
split apart my date input data, and save each piece into month, day, and year columns.
Then I would simply query my database for year & month, then loop through these results to construct my $data[] array for each day.
Is this the correct way I should be approaching this problem? It seems very redundant to have a date column as well as month, day, and year columns. Can it be done with only the date (mm/dd/yyyy) column? Too simple? Too complex? I'd like to avoid giving the user more than one field for entering a date, and ultimately I'll have a jQuery date-picker to help ensure the proper data format.
I know this may seem like a simple problem, but I've failed to locate simple code examples online. Most of the ones I've found are out of date (CI instead of CI2), too complex for what I'm doing, or use daily content items which have URI segments that already contain the date (~/events/view/yyyy/mm/dd).
EDIT:
This is how my Model is presently setup:
return $this->db->get_where('events', array('yyyy' => $year, 'mm' => $month))->result_array();
You can leave everything as-is and just structure your query to return the month and year as separate columns:
in SQL:
SELECT id,
title,
description,
MONTH(date_field) as event_month,
YEAR(date_field) as event_year
FROM my_table
... etc ...
and in Active Record (taken from here):
$this->db->select('id');
$this->db->select('title');
$this->db->select('description');
$this->db->select("MONTH(date_field) AS event_month");
$this->db->select("YEAR(date_field) AS event_year");
$query = $this->db->get('my_table');
$results = $query->result();
Firstly, I changed my date column into the MySQL "date" format, yyyy-mm-dd, in order to take advantage of the built-in MySQL date functions.
My original $query is as follows, where the 'yyyy' and 'mm' are my redundant "year" and "month" columns:
$this->db->get_where('events', array('yyyy' => $year, 'mm' => $month))->result_array();
I simply changed it into the following using the built-in MySQL date functions:
$this->db->get_where('events', array('YEAR(date)' => $year, 'MONTH(date)' => $month))->result_array();
This solved the question. Now I no longer need to maintain the extra columns for "year" and "month".
Additionally, I can assign the "day" portion of the date column to a virtual column called dd by using the MySQL "alias" function:
$this->db->select('DAY(date) AS dd');
However, this would fail since it over-rides CI's default select('*'). So you'll have to select() all the relevant columns first or it will give an error:
$this->db->select('*');
$this->db->select('DAY(date) AS dd');
And putting it all together in the Model:
// select all relevant columns
$this->db->select('*');
/* use MySQL date functions to creates virtual column called 'dd' containing
"day" portion of the real 'date' column. */
$this->db->select('DAY(date) AS dd');
/* use MySQL date functions to match $year and $month to "year" and "month"
portions of real 'date' column. */
return $this->db->get_where('events', array('YEAR(date)' => $year, 'MONTH(date)' => $month))->result_array();

Complex query implying dates

I'd like to return the customers from Magento who where created the day before OR who where updated the day before. I tried to play with addFieldToFilter, without any success.
I also tried to manipulate Zend_Db_Select, no success.
So now I'm stuck!
Here are some of my tries :
$customer = Mage::getModel('customer/customer');
$customers = $customer
->getCollection()
->getSelect()
->where("updated_at >= ? AND updated_at <= ?",$this->getFrom(), $this->getTo())
->orWhere("e.created_at >= ? AND e.created_at <= ?", $this->getFrom(), $this->getTo());
Or
->addFieldToFilter(
array(
array('attribute'=>'updated_at', 'gteq'=>$this->getFrom()),
array('attribute'=>'created_at', 'gteq'=>$this->getFrom())
),
'',
'left'
);
Thanks
I'd recommend against directly manipulating the select unless it's absolutely necessary and you know exactly what's going on behind the scenes in your version of Magento.
The following syntax should handle the tricky parts for you
$c = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToFilter(array(
array('attribute'=>'updated_at','from'=>'2010-05-12','to'=>'2010-05-30'),
array('attribute'=>'created_at','from'=>'2010-05-12','to'=>'2010-05-13')
));
var_dump( (string) $c->getSelect());
var_dump(count($c));
all you'll need to do is drop in the date ranges you want.
It is enough to use updated_at as your filter attribute, because it is set to current datetime when a user is created. So by filtering with this field you will get both new users and those who are not new but were updated in the given period. Here's the code to look for users updated or created during the last 24 hours:
$customers = Mage::getModel('customer/customer')->getCollection();
$customers->addAttributeToFilter('updated_at', array('gt' => date("Y-m-d H:i:s", time()-60*60*24)));
foreach($customers as $customer) {
//do sth
}
Thanks to Alan and Silvo, here is what I wrote :
->addAttributeToFilter(array(
array('attribute'=>'updated_at','from'=>$this->getFrom(),'to'=>$this->getTo())
));
Both answers were usefull. Thank you!

How do I query in cakephp, if the date in the field 'created' of model 'listings' is more than 2 weeks ago?

I have a model 'listing' with a field 'created' which is in a datetime format.
I need to list in a view all listings that were created over 2 weeks ago.
An extra thing if possible is to somehow mark them as expired.
This is in cakePhp 1.27
Hi I think you can use a simple script to do that in cake.
function meScript(){
// first load your model if necessary
$listingModel = ClassRegistry::init('Listing');
// Then set your date margin to , two weeks back
$date_margin = date("Y-m-d H:i:s", strtotime('-2 week')) ;
// now retrieve all records that were created over 2 weeks ago
$listings = $listingModel ->find('all', array(
'conditions' => array('created <' => $date_margin),
)
);
}
That's pretty much it. Since the margin date is in "Y-m-d H:i:s" format, the " 'created <' => $date_margin" condition will retrieve all records that were created before that date.
As for the next step of marking them as expired:
Simply loop through the results and use their ids to set your 'expired' field (or whatever it is called in your database table) to 'true'.

Categories