Symfony - 按月、年搜索表中的日期时间字段

发布于 2024-10-14 15:16:22 字数 271 浏览 1 评论 0原文

我正在尝试在前端模块上创建一个搜索过滤器,它将按 2 个字段进行过滤,这两个字段是

我的数据库表中有项目的月份和年份,其中有一个日期时间字段。

我希望能够创建一个搜索,如果我从 2 个下拉列表中选择 1 月和 2010 年,则所有具有日期时间的项目如下:

2010-01-24 10:50:52

2010-01-25 10: 50:52

将列出

我正在使用 symfony 1.4 和 Propel ORM

谢谢

I am trying to create an search filter on a frontend module, that will filter by 2 fields, which are months and years

I have items in my db table, that have a datetime field.

I'd like to be able to create a search, where If I select January and 2010 from the 2 drop downs, then all items that have datetimes like:

2010-01-24 10:50:52

2010-01-25 10:50:52

Will be listed

I am using symfony 1.4 and Propel ORM

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

四叶草在未来唯美盛开 2024-10-21 15:16:22

为什么不尝试创建 2 个日期并检查该日期是否在它们之间,例如 (2010-01-01 >= $date && 2010-01-31 <= $date )。如果是这样,那么您的范围和所有巧合都会出现。

如果您绝对必须检查月份和年份,我建议使用诸如 YEAR(date) = $yourDate 和 Month(date) = $yourMonth 之类的函数,此函数应符合自定义标准,并且可能如下所示:

$criterias->addCriteria(TablePeer::DATE_ATTRIBUTE,"YEAR(". TablePeer::DATE_ATTRIBUTE .") = $year",Criteria::CUSTOM);
$criterias->addCriteria(TablePeer::DATE_ATTRIBUTE,"MONTH(". TablePeer::DATE_ATTRIBUTE .") = $month",Criteria::CUSTOM);

这是指向的链接MysqlDateFunctions

Why dont you try to create 2 date and check if that date is between them, for example (2010-01-01 >= $date && 2010-01-31 <= $date ). If so, then your in range and all coincidences will appear.

If you absolutely have to check for month and year i recommend using functions like YEAR(date) = $yourDate and Month(date) = $yourMonth, this functions should go along with a CUSTOM criteria and could look like:

$criterias->addCriteria(TablePeer::DATE_ATTRIBUTE,"YEAR(". TablePeer::DATE_ATTRIBUTE .") = $year",Criteria::CUSTOM);
$criterias->addCriteria(TablePeer::DATE_ATTRIBUTE,"MONTH(". TablePeer::DATE_ATTRIBUTE .") = $month",Criteria::CUSTOM);

Here is a link to MysqlDateFunctions

浅唱々樱花落 2024-10-21 15:16:22

我在一个应用程序中有一些非常相似的东西。我使用 sfFormExtraPlugin 作为精美的日期小部件。

我的模型是“投诉”,我的行动是“探索”。

lib/form/ExploreForm.php:

class ExploreForm extends BaseForm
{
  public function configure()
  {

    $this->setWidgets
      (array(
             'explore_range' => new sfWidgetFormDateRange
             (array(
                    'from_date'   => new sfWidgetFormJQueryDate(),
                    'to_date'   =>  new sfWidgetFormJQueryDate(),
                    'label'   =>  'Date of Service ranging ',
                    )
              )
             )
       );

    $this->setValidators(array(
                               'explore_range'       => new sfValidatorDateRange
                               (array(
                                      'required' => true,
                                      'from_date' => new sfValidatorDate(array('required' => false)),
                                      'to_date' => new sfValidatorDate(array('required' => false))
                                      )),
                               'from'   =>  new sfValidatorPass(),
                               'to'   =>  new sfValidatorPass()
                               )
                         );

  }
}

apps/frontend/modules/complaint/templates/exploreSuccess.php:

<form action="<?php echo url_for('complaint/explore') ?>" method="GET">
  <input type="submit" value="Change date range" style="float:right" />
  <ul>
<?php echo $form->renderUsing('list')  ?>
  </ul>
</form>

在apps/frontend/modules/complaint/actions/中actions.class.php:
公共函数executeExplore($request)
{
// 默认值:本月第一天 - 1 年

  $this->form = new ExploreForm(array(
                'explore_range'   =>  array (
                             'from'   =>  $a_year_ago,
                             'to'   =>  $last_of_last_month
                             )
                  ));

  if ($request->hasParameter('explore_range') ) {
$this->form->bind( array('explore_range' => $request->getParameter('explore_range')) );
$this->logMessage("bound", "debug");
if ($this->form->isValid()) {
  $this->form_values = $this->form->getValues(); # cleaned
  $this->logMessage("validation WIN", "debug");
}
else {
  $this->logMessage("validation FAIL", "debug");
  $this->form_values = $this->form->getDefaults();
}

  }
  else {
$this->logMessage("no explore_range param", "debug");
$this->form_values = $this->form->getDefaults();
  }

  $this->from = $this->form_values['explore_range']['from'];
  $this->to = $this->form_values['explore_range']['to'];


  /* complaints per month */
  $this->complaints_by_month = ComplaintTable::getMonthCounts($this->from, $this->to);


  // ...

}

实际查询在模型中,lib/model/doctrine/ComplaintTable.class.php

public static function getMonthCounts($from, $to) {

  $connection = Doctrine_Manager::connection();
  $query = <<<ENDSQL
    SELECT year(`date`) as y, month(`date`) as m, count(*) as c
    FROM `complaints`.`complaint`
    WHERE `date` BETWEEN ? AND ?
    GROUP BY year(`date`), month(`date`)
ENDSQL;

  $statement = $connection->execute($query, array($from, $to));

  $result = array();
  while ($row = $statement->fetch()) {
    $result[ sprintf("%04d-%02d",$row[0], $row[1]) ] = $row[2];
  }

  return self::addZeroRows($result, $from, $to);
}

public static function addZeroRows($set, $from, $to) {
  /* insert zero counts for months with no count */
  $from_fields = date_parse($from);
  $to_fields = date_parse($to);
  $start_y = $from_fields['year'];
  $end_y = $to_fields['year'];
  $start_m = $from_fields['month'];
  $end_m = $to_fields['month'];

  $i = 0;
  for ( $y = $start_y;  $y <= $end_y;  $y++ ) {
    for (   $m = ($y == $start_y ? $start_m : 1) ;
            ($y == $end_y && $m <= $end_m) || ($y < $end_y && $m <= 12);
            $m++
            ) {
      $y_m = sprintf("%04d-%02d",$y,$m);
      if ( !isset( $set[$y_m] ) ) {
        $set[$y_m] = 0;
      }
      if ($i++ > 100) {  // don't infinitely loop... you did it wrong
        return $set;
      }
    }
  }


  ksort($set);
  return $set;
}

现在,我正在使用 Doctrine,因此您必须在模型部分将其翻译成 Propelese,并且您可能不会执行我在这里所做的“按月细分的统计数据”,但它应该可以帮助您继续前进。祝你好运!

I've got something very similar in an app. I'm using the sfFormExtraPlugin for fancy date widgets.

My model is "Complaint" and my action is "Explore".

lib/form/ExploreForm.php:

class ExploreForm extends BaseForm
{
  public function configure()
  {

    $this->setWidgets
      (array(
             'explore_range' => new sfWidgetFormDateRange
             (array(
                    'from_date'   => new sfWidgetFormJQueryDate(),
                    'to_date'   =>  new sfWidgetFormJQueryDate(),
                    'label'   =>  'Date of Service ranging ',
                    )
              )
             )
       );

    $this->setValidators(array(
                               'explore_range'       => new sfValidatorDateRange
                               (array(
                                      'required' => true,
                                      'from_date' => new sfValidatorDate(array('required' => false)),
                                      'to_date' => new sfValidatorDate(array('required' => false))
                                      )),
                               'from'   =>  new sfValidatorPass(),
                               'to'   =>  new sfValidatorPass()
                               )
                         );

  }
}

apps/frontend/modules/complaint/templates/exploreSuccess.php:

<form action="<?php echo url_for('complaint/explore') ?>" method="GET">
  <input type="submit" value="Change date range" style="float:right" />
  <ul>
<?php echo $form->renderUsing('list')  ?>
  </ul>
</form>

In apps/frontend/modules/complaint/actions/actions.class.php:
public function executeExplore($request)
{
// default: the first day of this month - 1 year

  $this->form = new ExploreForm(array(
                'explore_range'   =>  array (
                             'from'   =>  $a_year_ago,
                             'to'   =>  $last_of_last_month
                             )
                  ));

  if ($request->hasParameter('explore_range') ) {
$this->form->bind( array('explore_range' => $request->getParameter('explore_range')) );
$this->logMessage("bound", "debug");
if ($this->form->isValid()) {
  $this->form_values = $this->form->getValues(); # cleaned
  $this->logMessage("validation WIN", "debug");
}
else {
  $this->logMessage("validation FAIL", "debug");
  $this->form_values = $this->form->getDefaults();
}

  }
  else {
$this->logMessage("no explore_range param", "debug");
$this->form_values = $this->form->getDefaults();
  }

  $this->from = $this->form_values['explore_range']['from'];
  $this->to = $this->form_values['explore_range']['to'];


  /* complaints per month */
  $this->complaints_by_month = ComplaintTable::getMonthCounts($this->from, $this->to);


  // ...

}

And the actual query is in the model, lib/model/doctrine/ComplaintTable.class.php:

public static function getMonthCounts($from, $to) {

  $connection = Doctrine_Manager::connection();
  $query = <<<ENDSQL
    SELECT year(`date`) as y, month(`date`) as m, count(*) as c
    FROM `complaints`.`complaint`
    WHERE `date` BETWEEN ? AND ?
    GROUP BY year(`date`), month(`date`)
ENDSQL;

  $statement = $connection->execute($query, array($from, $to));

  $result = array();
  while ($row = $statement->fetch()) {
    $result[ sprintf("%04d-%02d",$row[0], $row[1]) ] = $row[2];
  }

  return self::addZeroRows($result, $from, $to);
}

public static function addZeroRows($set, $from, $to) {
  /* insert zero counts for months with no count */
  $from_fields = date_parse($from);
  $to_fields = date_parse($to);
  $start_y = $from_fields['year'];
  $end_y = $to_fields['year'];
  $start_m = $from_fields['month'];
  $end_m = $to_fields['month'];

  $i = 0;
  for ( $y = $start_y;  $y <= $end_y;  $y++ ) {
    for (   $m = ($y == $start_y ? $start_m : 1) ;
            ($y == $end_y && $m <= $end_m) || ($y < $end_y && $m <= 12);
            $m++
            ) {
      $y_m = sprintf("%04d-%02d",$y,$m);
      if ( !isset( $set[$y_m] ) ) {
        $set[$y_m] = 0;
      }
      if ($i++ > 100) {  // don't infinitely loop... you did it wrong
        return $set;
      }
    }
  }


  ksort($set);
  return $set;
}

Now, I'm using Doctrine so you'll have to do a bit of translation into Propelese in the model part, and you may not be doing the "statistics broken down by month" thing I'm doing here, but it should help you get going. Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文