How to pass a variable in the variable var $paginate with CakePHP - cakephp

My pagination worked perfectly like this :
var $paginate = array(
'Article' => array(
'conditions' => array(
'Article.visible' => true),
'order' => array('Article.creation_date DESC', 'Article.id DESC'),
'limit' => 11
)
);
But I want to filter my articles with a publication date like this
var $paginate = array(
'Article' => array(
'conditions' => array(
'Article.visible' => true,
'Article.publication_date <= ' => date('Y-m-d H:i:s')),
'order' => array('Article.creation_date DESC', 'Article.id DESC'),
'limit' => 11
)
);
But the date() function does not seem to be accepted.
It's not the good syntax.
Does anyone can help me?
Thanks a lot in advance.

If you want to do this, you will have to use $this->paginate = array() either in the action that you are paginating in, or in the __construct() function.
You cannot execute functions like that when the object is instantiated.
This is true for any type of method call at runtime.

You can't use a function in the declaration of an array at the class level. What you could do is to use a beforeFilter() callback in your controller to initialize the $paginate variable like this:
function beforeFilter()
{
parent :: beforeFilter();
$this->paginate = array(
'Article' => array(
'conditions' => array(
'Article.visible' => true,
'Article.publication_date <=' => date('Y-m-d H:i:s')),
'order' => array('Article.creation_date DESC', 'Article.id DESC'),
'limit' => 11
)
);
}

Related

Cakephp pagination using contain produces "not associated" warning

I've got the following models:
Run->hasMany ActualResult
ActualResult belongs to Status
When I view an ActualResult, Cake gets the corresponding Status without straight out of the box.
When I view a Run, I want to paginate the ActualResults. I have managed to get this to almost work with the following code in RunsController::view():
public function view($id = null) {
if (!$this->Run->exists($id)) {
throw new NotFoundException(__('Invalid run'));
}
$this->Run->contain ( 'Pack', 'User', 'Status');
$options = array('conditions' => array('Run.' . $this->Run->primaryKey => $id));
$run = $this->Run->find('first', $options);
$this->set('run', $run);
// Paginate the ActualResults
$this->paginate = array(
'contain' => array('Status'),
'order' => 'ActualResult.format',
'limit'=>5 ,
'conditions' => array('ActualResult.run_id' => $id)
);
$actualResults = $this->Paginator->paginate('ActualResult');
$this->set('actualResults',$actualResults);
}
The problem is that I get a warning:
Warning (512): Model "ActualResult" is not associated with model "Status" [CORE\Cake\Model\Behavior\ContainableBehavior.php, line 343
Something v. similar works for me in another model association, and as mentioned view() in ActualResultController works fine, so I am stumped.
Can anyone help?
Here are the model assocations:
In Run.php:
public $hasMany = array(
'ActualResult' => array(
'className' => 'actual_result',
'foreignKey' => 'run_id',
'dependent' => true,
'finderQuery' => 'SELECT ActualResult.*, Txn.name, Status.name FROM actual_results AS ActualResult, txns as Txn, codes AS Status WHERE ActualResult.run_id = {$__cakeID__$} and Txn.id = ActualResult.txn_id and (Status.code = ActualResult.status and Status.code_type = "ARS");'
)
);
In ActualResult.php
public $belongsTo = array(
'Run' => array(
'className' => 'Run',
'foreignKey' => 'run_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Status' => array(
'class`enter code here`Name' => 'Code',
'foreignKey' => 'status',
'conditions' => 'code_type = "ARS"',
'fields' => '',
'order' => ''
)
);

Cake PHP - How to access a special Model found by Pagination?

I have the following Code to get a special model related to another model related to actual object: (I want the Entry-model - in the Rubric-model-view)
$this->paginate = array(
'Entrieslocation' => array(
'conditions' => array('Entrieslocation.rubric_id' => $this->Rubric->id, 'Entrieslocation.subrubric_id' => '0'),
'joins' => array(
array(
'alias' => 'Entry',
'table' => 'entries',
'type' => 'INNER',
'conditions' => 'Entry.id = Entrieslocation.entry_id'
)
)
)
);
Then I thought I could get it by something like this:
$this->set('entries', $this->paginate('Entry'));
But the variable is empty, how can I access the Entries inside the Pagination in the view?
The Query generated by the code above is correct, I checked it by entering the query into phpmyadmin. So how can I access the result (only the Entries)?
Thanks for your help :)
First of all you must define $paginate variable below controller class. For example
class UsersController extends AppController {
public $paginate = array();
}
Then in your action follow following patter to get the paginated result.
$this->paginate = array(
'recursive' => -1,
'limit' => 10,
'conditions' => array('Your conditions'),
'fields' => array('Entry.*, Entrieslocations.*'),
'joins' => array(
array(
'table' => 'Entrieslocations',
'alias' => 'Entrieslocation',
'type' => 'inner',
'conditions' => 'Entry.id = Entrieslocation.entry_id'
),
),
'order' => array(
'Entry.id' => 'desc'
)
);
$entries = $this->paginate('Entry');
To pass result set to the view use following:
$this->set('entries', $entries);

Joining models in cake php

I have this NPO table which has one template. A template in turn has a theme. I want to retrieve which theme was selected by Npo.
I have following relation setup:
NPO - template on npo.id = template.npoid Template - theme on theme.id
= template.template_theme_id
And I am using:
$this->Npo->bindmodel(array(
'hasOne' => array(
'NpoTemplate' => array(
'className' => 'NpoTemplate'
)
)
), false);
$this->NpoTemplate->bindmodel(array(
'hasOne' => array(
'TemplateTheme' => array(
'className' => 'TemplateTheme',
'fields' => 'TemplateTheme.html'
)
)
), false);
$arrUserSite = $this->Npo->find('first', array(
'conditions'=> array(
'Npo.address' => $user
)
));
But it does not fetch anything from TemplateTheme. Instead it writes a seperate query for this table and does not consider it in the join.
I have set recursive level to 3
Please help. I don't really understand how the cake association works.
Regards
Himanshu Sharma
Try setting up your relationships in a single bindModel() call.
$this->Npo->bindmodel(array(
'hasOne' => array(
'NpoTemplate' => array(
'foreignKey' => false,
'conditions' => array(
'Npo.id = NpoTemplate.npoid'
)
),
'TemplateTheme' => array(
'foreignKey' => false,
'conditions' => array(
'NpoTemplate.template_theme_id = TemplateTheme.id'
)
)
)
));
$arrUserSite = $this->Npo->find('first', array(
'conditions' => array(
'Npo.address' => $user
)
));
You'll probably need to tweak the bindModel setup because I'm not 100% sure of your database structure. Good luck.

cakephp paginate: data from different tables

i have "PostsController" controller and in this controller i need get all user list.
So i need get data no from "Posts" DB table, bu from "Users".
In function I make this paginate:
$this->paginate = array(
'user' => array(
'limit' => 2,
'order' => array(
'user.id' => 'asc',
),
'table' => 'users'
),
);
$users = $this->paginate('user');
$this->set('users', $users);
But always get empty result, why?
And show this error:
Warning (512): Controller::paginate() - can't find model user in controller PostsController [CORE\cake\libs\controller\controller.php, line 1106]
Model name have first letter capitalized, so try
$this->paginate = array(
'User' => array(
'limit' => 2,
'order' => array(
'User.id' => 'asc',
),
'table' => 'users'
),
);
$users = $this->paginate('User');
$this->set('users', $users);

CakePhp: On the fly associations using a re-named Model field?

I'm trying to use on the fly associations to trim down the data I retrieve, but the model I'm using is associated to other models with a re-named field because I have 2 of the same models associated with it.
So, here's the model, say 'test', that has two 'user' fields, both related to the User model.
In the model:
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'User_Watched' => array(
'className' => 'User',
'foreignKey' => 'user_id_watched'
)
);
When I retrieve data related to 'test', I want to only retrieve particular data linked to the 'User' and 'User_Watched' fields without any other nested information.
But when I do:
$this->User->unbindModel(array('hasMany' => array('something1', 'something2')), false);
then something1 and something2 data does not show up for the 'User' field of model 'test', but is still retrieved for the 'User_watched' field.
Can I not retrieve unwanted data for the 'User_watched' field?
Hope this makes sense... :)
KcYxA,
Containable behavior might help a lot in this case, as benjamin mentioned, your "find" queries would look like:
$this->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array('UserWatched')
));
In this case, you won't have to use unbindModel method. In this example, you'll get User and UserWatched data.
If you need only User data from "find", then tell Cake to "$this->User->contain();" so it won't go further then User model.
to use on the fly associations to trim
down the data I retrieve
Good idea.
'foreignKey' => 'user_id_watched'
should possibly be:
'foreignKey' => 'user_watched_id'.
Edit 1: At least this would make sense according to my current understanding. If user_id is a correct foreign key(FK), which cakephp uses to unbind the relations, but user_id_watched isn't, than your described behavior is explained.
Edit 2: The Containable behavior gives you another tool for controlling associated models.
Change $primaryKey in fly, run controller
Sample:
// Models
//....
class PreProductoDescripcion extends AppModel {
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'id_producto_descripcion';
//....
//....
}
class SenasaPedidosDetalles extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'cod_tango';
public $belongsTo = array(
'SenasaPedidos' => array(
'className' => 'SenasaPedidos',
'foreignKey' => 'senasa_pedidos_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'PreProductoDescripcion' => array(
'className' => 'PreProductoDescripcion',
'foreignKey' => 'cod_tango',
//'conditions' => array('SenasaPedidosDetalles.cod_tango' => 'PreProductoDescripcion.codigo'),
'fields' => '',
'order' => ''
)
);
//....
#
// Controller Fly
//...
$this->SenasaPedidos->Behaviors->load('Containable');
$this->SenasaPedidos->SenasaPedidosDetalles->PreProductoDescripcion->primaryKey = 'codigo';
$datos = $this->SenasaPedidos->find(
'first', array(
'fields' => array( 'SenasaPedidos.*' ),
'conditions' => array( 'SenasaPedidos.id' => $id ),
'contain' => array(
'Usuarios' => array(
'fields' => array( 'Usuarios.apellido_nombre' )
),
'Clientes' => array(
'fields' => array( 'Clientes.razon_social' )
),
'Provincias' => array(
'fields' => array( 'Provincias.nombre' )
),
'Transportes' => array(
'fields' => array( 'Transportes.razon_social' )
),
'SenasaPedidosDetalles' => array(
'fields' => array( 'SenasaPedidosDetalles.*' ),
'PreProductoDescripcion' => array(
'fields' => array(
'PreProductoDescripcion.id_producto_descripcion',
'PreProductoDescripcion.descripcion'
)
)
),
)
));
//...

Resources