I'm trying to use find('list') method, but without success.
When I try to LIST the types of paying, just one table of database was showing correct, another is doing correct SQL but it's returning me null (even with the sql get rows).
If try to read ONE field of Tpagamento, it works
If I change the displayField of Tpagamento to 'id', it works, but the query only show the id.
Here is the scenario:
(Parcelamento and Tpagamento have the same databasefields)
View Method:
public function view($id = null) {
$this->Ordemservico->id = $id;
if (!$this->Ordemservico->exists()) {
$this->Session->setFlash('This Order does not exist..','flash_error');
$this->redirect(array('action' => 'index'));
}
//Listing all orders // THIS IS WORKING
$os = $this->Ordemservico->read(null, $id);
$this->set('os',$os);
//Listing the types of paying //THIS IS WORKING
$this->loadModel('Parcelamento');
$parcelamentos = $this->Parcelamento->find('list');
$this->set('parcelamentos',$parcelamentos);
$this->loadModel('Tpagamento'); // THIS IS NOT WORKING
$tpagamento = $this->Tpagamento->find('list');
$this->set('tpagamento ',$tpagamento );
//Read a specific type of paying, WORK!
$this->loadModel('Tpagamento'); // THIS IS WORKING
$tpagamentos = $this->Tpagamento->read(null,'5');
$this->set('tpagamentos',$tpagamentos);
}
OrdemServico Model:
class Ordemservico extends AppModel {
public $displayField = 'cliente_id';
public $belongsTo = array(
'Tpagamento' => array(
'className' => 'Tpagamento',
'foreignKey' => 'tpagamento_id',
),
'Parcelamento' => array(
'className' => 'Parcelamento',
'foreignKey' => 'parcelamento_id',
),
);
}
Tpagamento Model:
class Tpagamento extends AppModel {
public $useTable = 'tpagamentos';
public $displayField = 'nome';
public $hasMany = array(
'Ordemservico' => array(
'className' => 'Ordemservico',
'foreignKey' => 'tpagamento_id',
),
);
}
Parcelamento Model:
class Parcelamento extends AppModel {
public $displayField = 'nome';
public $hasMany = array(
'Ordemservico' => array(
'className' => 'Ordemservico',
'foreignKey' => 'parcelamento_id',
),
);
}
Generated SQL DUMP:
4 SELECT `Parcelamento`.`id`, `Parcelamento`.`nome` FROM `tereza`.`parcelamentos` AS `Parcelamento` WHERE 1 = 1 5 5 0
5 SELECT `Tpagamento`.`id`, `Tpagamento`.`nome` FROM `tereza`.`tpagamentos` AS `Tpagamento` WHERE 1 = 1 4 4 0
6 SELECT `Tpagamento`.`id`, `Tpagamento`.`nome`, `Tpagamento`.`created`, `Tpagamento`.`modified` FROM `tereza`.`tpagamentos` AS `Tpagamento` WHERE `Tpagamento`.`id` = 5 LIMIT 1 1 1 0
In the Config/database.php I setted: 'encoding' => 'utf8'
The reason to work In one table and not another is because in one table (tpagamentos) I have special characters and in another not (parcelamentos).
To show two fields in a list use the following syntax:
$this->Parcelamento->find('list', array('fields' => array('id', 'other_field_name')));
Related
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.
I have a Product model and an Image model. They have an HABTM association.
Some Images exist but they are not linked to the product.
Now when I save a Product I would like to link it to some unlinked images using an array of images IDs (I MUST use this array).
Here's my code:
class Image extends AppModel {
public $useTable = 'images';
var $hasAndBelongToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'products_images',
'foreignKey' => 'id_image',
'associationForeignKey' => 'id_product'
)
);
}
class Product extends AppModel {
public $useTable = 'products';
var $hasAndBelongToMany = array(
'Image' => array(
'className' => 'Image',
'joinTable' => 'products_images',
'foreignKey' => 'id_product',
'associationForeignKey' => 'id_image'
)
);
}
class productsController extends AppController {
public $name = 'Products';
public $uses = array('Products', 'File');
public function add() {
if (!empty($this->data)) {
$this->Product->create();
if ($this->AnnuncioImmobiliare->save($this->request->data)) {
$idProduct = $this->Product->getLastInsertID();
$this->request->data['imagesIds'] = array("1", "2", "3");
if(isset($this->request->data['imagesIds'])){
foreach($this->request->data['imagesIds'] as $imageId){
$this->Image->id = $imageId;
$this->Image->save(array('Product'=>array('id'=>$idProduct)));
}
}
}
}
}
}
This doesn't work. Where am I wrong?
1) you didn't provide the data, so we can't verify it's in the correct format.
2) you're using "save()" not "saveAll()" or "saveMany()" or "saveAssociated()". Just using "save()" will not save any associated model data.
I found a solution myself!
I observed how CakePHP handles $this->data->response array when data is passed using an input automagically created for HABTM associations and I found the array should be formatted like this:
array(
'Product' => array(
'name' => 'myProduct',
'id' => ''
),
'Image' => array(
'Image'=>array(
0 => '1',
1 => '2',
2 => '3'
)
)
)
So the correct code for the controller is
class productsController extends AppController {
public $name = 'Products';
public $uses = array('Products', 'File');
public function add() {
if (!empty($this->data)) {
$this->Product->create();
if (isset($this->request->data['imagesIds'])) {
$this->request->data['Image'] = array('Image' => $this->request->data['imagesIds']);
}
if ($this->AnnuncioImmobiliare->save($this->request->data)) {
/* success */
}
}
}
}
That's it! I hope you find this useful.
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?
First of all, sorry if this sounds too simple. I'm new to cakePHP by the way.
My objective is to expand the team_id in season controller where it linked thru standings table.
My current model rule are:
Each season has many standings
Each standings denotes a team.
Basically is a many to many relation between season and team = standings.
Here's my SeasonController:
class SeasonsController extends AppController
{
public $helpers = array('Html', 'Form');
public function view($id)
{
$this->Season->id = $id;
$this->set('season', $this->Season->read());
}
}
When I browse a single season thru /cakephp/seasons/view/1, the $season array shows:
Array
(
[Season] => Array
(
[id] => 1
[name] => English Premier League 2013/2014
[start] => 1350379014
[end] => 0
)
[Standing] => Array
(
[0] => Array
(
[id] => 1
[team_id] => 1
[win] => 1
[lose] => 0
[draw] => 1
[GF] => 5
[GA] => 4
[season_id] => 1
[rank] => 1
)
[1] => Array
(
[id] => 2
[team_id] => 2
[win] => 0
[lose] => 1
[draw] => 1
[GF] => 4
[GA] => 5
[season_id] => 1
[rank] => 2
)
)
)
The result only shows team_id, but how can I get further expansion for team_id?
I have put below in my Team's model, but still doesn't auto linked. Below are all my models:
class Team extends AppModel
{
public $name = 'Team';
public $hasMany = array(
'Standing' => array(
'className' => 'Standing'
));
}
class Season extends AppModel
{
public $name = 'Season';
public $hasMany = array(
'Standing' => array(
'className' => 'Standing'
));
}
class Standing extends AppModel
{
public $name = 'Standing';
public $belongsTo = array(
'Team' => array(
'className' => 'Team',
'foreignKey' => 'team_id',
),
'Season' => array(
'className' => 'Season',
'foreignKey' => 'season_id',
),
);
}
TLDR:
Use CakePHP's [Containable] behavior.
Explanation & Code example:
"Containable" lets you "contain" any associated data you'd like. Instead of "recursive", which blindly pulls entire levels of data (and can often cause memory errors), "Containable" allows you to specify EXACTLY what data you want to retrieve even down to the field(s) if you'd like.
Basically, you set your model to public $actsAs = array('Containable'); (I suggest doing that in your AppModel so Containable is available for all models). Then, you pass a "contain" array/nested array of the associated models you want to retrieve (see below example).
After reading about it and following the instructions, your code should look similar to this:
public function view($id = null)
{
if(empty($id)) $this->redirect('/');
$season = $this->Season->find('first', array(
'conditions' => array(
'Season.id' => $id
),
'contain' => array(
'Standing' => array(
'Team'
)
)
);
$this->set(compact('season'));
}
Once you get more comfortable with CakePHP, you should really move functions like this into the model instead of having them in the controller (search for "CakePHP Fat Models Skinny Controllers"), but for now, just get it working. :)
Use :
$this->Season->id = $id;
$this->Season->recursive = 2;
$this->set('season', $this->Season->read());
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...