douyicao2199 2014-03-19 19:44
浏览 40
已采纳

我如何在数据库cakephp中为一年的日期字段创建一个select选项

hello I have a date field en mi DB "dateToday" now I need make a selection of all year and store them in an array

2013-01-11

2014-03-12

2014-05-21

2013-11-15

2014-12-19

2014-03-17

2015-09-01

2015-04-24

my array will be (2013, 2014, 2015)

into my code I probe somthing but no found.

model

SoyaProductorCompra.php

   <?php
/**
* 
*/
class SoyaProductorCompra extends AppModel
{
    public $useTable = 'soyaproductorcompra';
    public $primaryKey = 'id';  
    public $belongsTo = array('User');

    public function getYears()
    {
        return $this->SoyaProductorCompra->find('all', array('fields' => 'DISTINCT YEAR(fecharegistro) as distinct_year'));
    }
}

?>

but this no found in my view

SoyasController.php

<?php
/**
* 
*/
class SoyasController extends AppController
{

    public function cano($id = null)
    {
        $this->loadModel('Soya');

        $this->loadModel("SoyaProductorCompra");
        $years = $this->SoyaProductorCompra->getYears();

        if (!$id) {
            $this->Session->setFlash('Porfavor provea un id de usuario');
            $this->redirect(array('action'=>'index'));
        }

        $user = $this->Soya->findById($id);
        if (!$user) {
            $this->Session->setFlash('El id proporcionado no es valido');
            $this->redirect(array('action'=>'index'));
        }
        if (!$this->request->data) {
            $this->request->data = $user;
        }
    }
}

Error: Call to a member function find() on a non-object

File: SoyaProductorCompra.php

Line: return $this->SoyaProductorCompra->find('all', array('fields' => 'DISTINCT YEAR(fecharegistro) as distinct_year'));

  • 写回答

2条回答 默认 最新

  • drus40229 2014-03-19 19:48
    关注

    From your controller, you can get the distinct years from your model like this:

    $years = $this->YourModel->find('all', array(
        'fields' => 'DISTINCT YEAR(yourdatefield) as distinct_year'
    ));
    

    Then, populate an array:

    $distinct_years = array();
    foreach($years as $year) {
        $distinct_years[] = $year[0]['distinct_year'];
    }
    

    ... and set it to be available in your view:

    $this->set(compact('distinct_years'));
    

    Then in your view:

    print_r($distinct_years);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录