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'));
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);
You don't have to call the model inside itself, because it's stored on this
variable. So:
public function getYears()
{
return $this->find('all', array('fields' => 'DISTINCT YEAR(fecharegistro) as distinct_year'));
}