How can I do an arbitrary level of recursion in CakePHP - cakephp

I have a blog post model:
App::uses('AppModel', 'Model');
class BlogPost extends AppModel {
public $primaryKey = "ID";
public $useDbConfig = 'dev_blog';
public $useTable = 'posts';
public $hasMany = array(
'BlogComment' => array(
'foreignKey' => 'comment_post_ID',
'className' => 'BlogComment',
'order' => 'BlogComment.comment_date DESC',
'conditions' => array(
'BlogComment.comment_approved' => '1',
'BlogComment.comment_parent' => 0
)
)
);
}
And a blog comment model:
App::uses('AppModel', 'Model');
class BlogComment extends AppModel {
public $primaryKey = "comment_ID";
public $useDbConfig = 'dev_blog';
public $useTable = 'comments';
public $hasMany = array(
'Children' => array(
'className' => 'BlogComment',
'foreignKey' => 'comment_parent',
'order' => 'Children.comment_date DESC',
'conditions' => array(
'Children.comment_approved' => 1
)
)
);
}
In the controller, I set recursion on BlogPost equal to 2 and did a find:
$options = array(
'conditions' => array(
'BlogPost.ID' => $postID,
'BlogPost.post_status' => 'publish'
),
);
$post = $this->BlogPost->find('first', $options);
What this does is get the content of a particular blog post, all root comments and one level of replies to the root comments. It doesn't get a reply to a reply, though. How can I retrieve an arbitrary depth of replies?

Just don't use recursive at all. Ever.
Set it to -1 in the AppModel:
public $recursive = -1;
Then forget you even heard of it, and use CakePHP's awesome Containable Behavior to get the data you need.
Note: See the MANY other answers related to using CakePHP's Containable.

Related

Can't find model associated model data

i'm new in CakePHP and i'm having problems in an example i'm building to learn.
I'm building a plugin with 3 models (Categoria,Plato,Imagen)
The relationships between them are the following:
Categoria - Plato (n-n)
Plato - Imagen (1-n)
If I go to Plato view, I get all Imagen by the relationship, but when I access through a category, I can't just reach the Imagen associated with each Plato. Why? What's the problem?
Models code:
Plato:
App::uses('AppModel', 'Model');
class Plato extends ErestaurantAppModel {
public $name = 'Plato';
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Categoria' => array(
'className' => 'Categoria',
'joinTable' => 'categorias_platos',
'foreignKey' => 'plato_id',
'associationForeignKey' => 'categoria_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
public $hasMany = array('Imagen' =>
array('foreingkey' => array('plato_id')));
}
Categoria:
App::uses('AppModel', 'Model');
class Categoria extends ErestaurantAppModel {
public $name = 'Categoria';
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Plato' => array(
'className' => 'Plato',
'joinTable' => 'categorias_platos',
'foreignKey' => 'categoria_id',
'associationForeignKey' => 'plato_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
}
Imagen:
App::uses('AppModel', 'Model');
class Imagen extends ErestaurantAppModel {
public $name = 'Imagen';
//public $actsAs = array('Containable');
public $belongsTo = array('Plato');
}
Finally, the code I'm launching when i go to a Categoria view.
App::uses('AppController', 'Controller');
class CategoriasController extends ErestaurantAppController {
public $uses = array('Erestaurant.Categoria');
public function index() {
$this->Categoria->recursive = 0;
$this->set('data', $this->Categoria->find('all'));
}
public function view($id = null) {
if (!$this->Categoria->exists($id)) {
throw new NotFoundException(__('Registro inválido.'));
}
/*
$this->Categoria->recursive = -1;
$options = array('conditions' =>
array('Categoria.'.$this->Categoria->primaryKey => $id),
'contain' => array(
'Plato' => array(
'Imagen'
)
)
);
*/
$this->Categoria->recursive = 2;
$options = array('conditions' =>
array('Categoria.'.$this->Categoria->primaryKey => $id));
$this->set('item', $this->Categoria->find('first', $options));
}
}
The commented code you see it's another way I tried, using Containable, but at the end I get error "Plato is not associated with model Imagen"
Database seems all ok, with each table created as needed (categorias, platos, imagens, categorias_platos) and with all foering keys created and trying to keep CakePHP default names.
Thank you!
To access deep relations you must use containable behavior. You have a definition of containable behavior in your model, but for some reason it is commented.
public $actsAs = array('Containable');
Uppon uncommenting this line in your Categoria, you can access deep relations in this way:
$this->Categoria->find('all', array(
'contain'=>array(
'Plato.Imagen'
)
));
...or something like this. For more information plase visit this link Containable Behavior

Cakephp search plugin - Search inside related model

Cliente hasMany Solicitud.
I am using CakeDC search plugin.
I need to search inside Solicitud where Cliente.nombre = "myValue". Is this even doable?
I paste what I have:
//SOLICITUD MODEL
public $actsAs = array('Search.Searchable', 'Containable');
public $filterArgs = array(
'nombre' => array('type' => 'like', 'field' => array('Cliente.nombre')),
);
I don't know if this is doable or I am fantasizing. Ideas?
You're fantasizing or didn't read the readme.md.
Let me shorten the example from the readme.md for you, it should become obvious:
class Article extends AppModel {
public $actsAs = array('Search.Searchable');
public $belongsTo = array('User');
public $filterArgs = array(
'title' => array('type' => 'like'),
'username' => array('type' => 'like', 'field' => array(
'User.username', 'UserInfo.first_name')),
);
Notice the Model.field notation for the username filter.

CakePHP 2.3 Model probleme getting data

sorry for my english and i'm new using CAKEPHP 2.3
i get a problem using model association where i can't get "joined data" ( i understand that cakephp get automatically joined data if models are set good , obviously i make it wrong )
I have 2 tables in my database:
departements (with the following columns)
-id
-name
-region_id ( region_id is a foreign key on regions(id) )
regions (with the following columns)
-id
-name
i make two models in cakePhp:
Region.php
<?php
class Region extends AppModel {
var $name = 'Region';
var $actsAs = array( 'Containable' );
public $hasMany = array(
'Departement' => array(
'className' => 'Departement',
'foreignKey' => 'region_id',
'dependent' => false
)
);
}
?>
Departement.php
<?php
class Departement extends AppModel {
var $name = 'Departement';
var $actsAs = array( 'Containable' );
public $belongsTo=array(
'Region' => array(
'className' => 'Region',
'foreignKey' => 'region_id',
'dependent' => false
)
);
}
?>
in a another controller where i need departements and regions, i tryed many thinks but after yours i need your help please !!!
i make this :
first attempt:
<?php
class SignalementsController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Signalements';
var $uses = array('Signalements','Regions','Departements','Communes');
public $recursive = 4;
public function index() {
$departements = $this->Departements->find('all');
$this->set('departements', $departements);
}
}
who output in the index view:
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'name' => 'AIN',
'region_id' => '82'
)
),
(int) 1 => array(
'Departements' => array(
'id' => '10',
'name' => 'AUBE',
'region_id' => '21'
)
)
...
)
but there is no region joined automatically
second attempt: i change the find models from
$regions = $this->Regions->find('all');
$this->set('regions', $regions);
who output :
array(
(int) 0 => array(
'Regions' => array(
'id' => '11',
'name' => 'ILE-DE-FRANCE'
)
), ... );
but there is no departements joined automatically
last
$fields=array('Region.id','Region.nom','Departement.id','Departement.nom');
$all= $this->Regions->Departements->find('all',$fields);
/* or all this not working as execpted
$all= $this->Departements->Regions->find('all',$fields);
$all= $this->Departements->find('all',$fields);
$all= $this->Regions->find('all',$fields);
*/
$this->set('all', $all);
i try to get the regions data inside each departemts for exemple like this
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'nom' => 'AIN',
'region' => array( 'id' => '82', 'nom' => 'POITOU-CHARENTES')
)
),
but i get only this :
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'nom' => 'AIN',
'region_id' => '82'
)
),
If you have any idea please leave it
thank you very much
You are using Containable behaviour in your model, so try the find with this:
$departements = $this->Departement->find('all', array('contain' => 'Region'));
Also the maximum level for recursive is 2, setting it to 4 (or 1000) has the effect of 2.
Your ID is of type varchar and should be int.
Also, here is a stripped down version of your code
Region.php
<?php
class Region extends AppModel {
var $actsAs = array( 'Containable' );
public $hasMany = array( 'Departement' );
}
?>
Departement.php
<?php
class Departement extends AppModel {
var $actsAs = array( 'Containable' );
public $belongsTo=array( 'Region' );
}
?>
<?php
class SignalementsController extends AppController {
public $helpers = array('Html', 'Form');
var $uses = array('Signalements','Regions','Departements','Communes');
public function index() {
$this->Departement->recursive = 1;
$departements = $this->Departements->find('all');
$this->set('departements', $departements);
}
}
index.ctp
<?php print_r($departements); ?>
What does it give you?

CakePHP: Call to a member function on a non-object error with aliases

I keep getting a "Call to a member function on a non-object" error in the index function of one of my controllers. Here is the code:
class ModulesController extends AppController {
public $uses = array('Module', 'User');
public $scaffold;
function index() {
if ($this->request->is('get')) { //Technically unecessary but good practice
$email = AuthComponent::user('email');
$user = $this->Module->User->findByEmail($email);
//Code omitted
}
}
And this is my Module model:
class Module extends AppModel {
public $name = 'Module';
public $hasMany = array(
'Slide' => array(
'className' => 'Slide',
'foreignKey' => 'module_id',
'order' => 'Slide.position ASC' //Let's make sure that name is correct
));
public $belongsTo = array(
'Creator' => array(
'className' => 'User'));
public $hasAndBelongsToMany = array(
'OUser' => array(
'className' => 'User',
'joinTable' => 'modules_users',
'foreignKey' => 'module_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
));
} //Unnecessary code omitted
And this is the code for my user model:
class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
'OModule' => array( //Owner of Modules
'className' => 'Module',
'foreignKey' => 'user_id',
'order' => 'Module.created DESC'
));
public $hasAndBelongsToMany = array(
'Module' => array(
'className' => 'Module',
'joinTable' => 'modules_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'module_id',
'unique' => 'keepExisting',
));
} //Unnecessary code omitted
It is worth mentioning that User and Module have both a belongsTo and a HABTM relationship, so User has the aliases Creator and OUser respectively. In the code above, the findByEmail is trying to use the Creator relationship, but that gives me the same error.
My question is, how do I call the findByEmail() method without error?
Change:
$user = $this->Module->User->findByEmail($email);
To:
$user = $this->User->findByEmail($email);
Voila!
Reason:
Somehow, there is either 1) no relationship between Module and User, 2) a mistake in the relationship, or 3) your using an alias for either or both of them so that using Module->User wouldn't be correct.
You're loading the 'User' model anyway though, so there's no reason to go through the Module model to access it - just access it directly (like example above).

CakePHP: pagination with recursive queries not working as expected

I got this models:
class CompanyRestaurantRequest extends AppModel
{
public $name = "CompanyRestaurantRequest";
//public $actsAs = array('Containable');
public $hasMany = array(
"UserRestaurantRequestFeed" => array(
'dependent' => true
)
);
}
class UserRestaurantRequestFeed extends AppModel{
public $name = "UserRestaurantRequestFeed";
public $belongsTo = array("CompanyRestaurantRequest");
public $hasMany = array("UserRestaurantRequestFeedResponse");
}
class UserRestaurantRequestFeedResponse extends AppModel{
public $name = "UserRestaurantRequestFeedResponse";
public $belongsTo = array("UserRestaurantRequestFeed");
}
and I am trying to paginate CompanyRestaurantRequest like this:
$this->CompanyRestaurantRequest->recursive = 5;
$this->CompanyRestaurantRequestFeed->recursive = 5;
$this->paginate = array(
'limit' => 10,
'order' => array(
'CompanyRestaurantRequest.id' => 'desc'
)
);
$this->set('requests', $this->paginate("CompanyRestaurantRequest"));
The problem is that I get no CompanyRestaurantRequestFeedResponse.
I tried to attach ContainableBehavior to the CompanyRestaurantRequest model and I used contain key in paginate settings like this:
'contain' => array('CompanyRestaurantRequestFeedResponse');
Anything I try, I can not get those CompanyRestaurantRequestFeedResponses related to CompanyRestaurantRequestFeeds.
How can I make it work?
Thank you!
Intead of lines:
$this->paginate = array(
'limit' => 10,
'order' => array(
'CompanyRestaurantRequest.id' => 'desc'
)
);
At the top of the Controller where all var are declared add:
public $paginate = array(
'CompanyRestaurantRequest' => array(
'limit' => 10,
'order' => array(
'CompanyRestaurantRequest.id' => 'desc'
)
)
);
This should fix it...

Resources