简体   繁体   中英

Filter MySQL return by date range

I need to modify this object to return only entries for the last 100 days, but we do not have an entry for everyday so we need something more sophisticated to filter out the extra dates.

Current object:

$obj = YearToDate::get()->sort('ID', 'DESC')->limit(100);

Is it possible to filter by created date in the object definition? Or will I need to create a function to handle the filtering?

Here is the class:

class YearToDate extends DataObject {

// Create DB fields
private static $db = array(
    'Inches' => 'Text'
);

// Assign Weather to Weather
private static $belongs_many_many = array(
    'Weather' => 'Weather'
);

// Summary fields to show in gridfield
private static $summary_fields = array(
    'Created' => 'Date',
    'Inches' => 'Inches'
);

public function getCMSFields() {
    $fields = parent::getCMSFields();

    // Remove Fields
    $fields->removeByName('Weather');

    // Add DB fields to CMS tabs
    $fields->addFieldToTab('Root.Main', new TextField('Inches','Inches'));

    return $fields;
}

// Required Fields
function getCMSValidator() {
    return new RequiredFields(array('Inches'));
}

}

If you're using MySQL as underlying RDBMS, you can use MySQL date functions to query for entries from the last 100 days.

Something like this should work:

$list = YearToDate::get()
    ->sort('Created', 'DESC')
    ->where('"Created" >= DATE_SUB(NOW(), INTERVAL 100 DAY)')

So what this does, is remove 100 days from the current time ( NOW() ) and compare it to the Created date. If Created is bigger, then it's less than 100 days old.

That will strictly filter for the last 100 days, so if you don't have an entry per day or multiple entries per day, you might get less or more than 100 results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM