i have two models. Teacher and Subject joined by HABTM defined both ways. A teacher can teach many subjects and a subject can be taught by many teachers.my join table is subjects_teachers and have fields id,teacher_id and subject_id.
Fetching Teacher data from its model, i expect all teachers and their respective subjects ,
Fetching Subject data from its model i expect to also see the teachers teaching that particular subject
problem
on both instances, the associated model returns the correct number of records but the data is absent. i see [maximum depth reached] when i display the respective arrays.
I removed the id field from the join table and that fixed only the Teacher model.The Subject model still has the problem.
i just need to know what [maximum depth reached] means and why removing the id filed from the join table fixed the Teacher problem but not Subject.
also if its important i should mention that my Teacher model primary key field doesnt follow convention
SUBJECT model
public $hasAndBelongsToMany = array(
'Teacher' => array(
'className' => 'Teacher',
'joinTable' => 'subjects_teachers',
'foreignKey' => 'subject_id',
'associationForeignKey' => 'teacher_id',
'unique' => 'keepExisting'
)
);
Teacher Model
public $hasAndBelongsToMany = array(
'Subject' => array(
'className' => 'Subject',
'joinTable' => 'subjects_teachers',
'foreignKey' => 'teacher_id',
'associationForeignKey' => 'subject_id',
'unique' => 'keepExisting'
)
);
Results from subject
array(
(int) 0 => array(
'Subject' => array(
'id' => '1',
'subject_code' => '121',
'subject_name' => 'Mathematics',
'compulsory' => true
),
'Teacher' => array(
(int) 0 => array(
[maximum depth reached]
),
(int) 1 => array(
[maximum depth reached]
),
(int) 2 => array(
[maximum depth reached]
)
)
),
Results from Teacher before removin id field
array(
'Teacher' => array(
'teacher_id' => '6',
'first_name' => 'George',
),
'Subject' => array(
(int) 0 => array(
'id' => '1',
'subject_code' => '121',
'subject_name' => 'Mathematics',
'compulsory' => true,
'SubjectsTeacher' => array(
[maximum depth reached]
)
)
Results after removing id field
'Subject' => array(
(int) 0 => array(
'id' => '1',
'subject_code' => '121',
'subject_name' => 'Mathematics',
'compulsory' => true
),
Your data exists, the debugger just wont display it because the depth option limits it. Use debug() (default depth = 25) or Debugger::dump()/exportVar() with a depth (second argument, defaults to 3) high enough for your deeply nested data.
See also
http://book.cakephp.org/2.0/en/development/debugging.html
http://api.cakephp.org/2.5/class-Debugger.html
It is related to model attribute recursive
http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
Related
I came across this post that gave an answer on how to do this but it's not quite working for me.
I have a model called SitePage which has many SitePageGroup which in turn has many SitePageContent
// SitePage Model
public $hasMany = array(
'SitePageGroup' => array(
'className' => 'FoCMS.SitePageGroup',
'foreignKey' => 'site_page_id',
'dependent' => FALSE,
),
);
// SitePageGroup Model
public $belongsTo = array(
'SitePage' => array(
'className' => 'FoCMS.SitePage',
'foreignKey' => 'site_page_id',
),
);
public $hasMany = array(
'SitePageContent' => array(
'className' => 'FoCMS.SitePageContent',
'foreignKey' => 'site_page_group_id',
'dependent' => FALSE,
),
);
// SitePageContent Model
public $belongsTo = array(
'SitePageGroup' => array(
'className' => 'FoCMS.SitePageGroup',
'foreignKey' => 'site_page_group_id',
),
);
Using the answer in that linked question I am seeing the parent model, SitePage being duplicated, but the associated models are being removed from the original and associated with the new one.
$record = $this->SitePage->find('first', array('condition' => array('SitePage.id' => $id)));
unset($record['SitePage']['id'], $record['SitePageGroup']['id'], $record['SitePageGroup']['SitePageContent']['id'] /* further ids */);
$this->SitePage->create();
$record['SitePage']['name'] = $record['SitePage']['name'].'-copy';
$record['SitePage']['friendly_name'] = $record['SitePage']['friendly_name'].' Copy';
if($this->SitePage->saveAll($record)){
$this->Session->setFlash('The site page has been saved', 'fo_message');
$this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash('The site page could not be saved. Please, try again.', 'fo_message');
}
Update
Debugging the record that I'm trying to reset I see the following
array(
'SitePage' => array(
'name' => 'test',
'friendly_name' => 'Test',
'order' => '82',
'created' => '2015-09-03 19:16:40',
'modified' => '2015-09-03 19:20:27'
),
'SitePageGroup' => array(
(int) 0 => array(
'id' => '55e88087-a4dc-4c37-89dc-f9c172b40463',
'site_page_id' => '55e88078-16c8-46ce-bf02-fa5372b40463',
'name' => 'group-1',
'friendly_name' => 'Group 1',
'order' => '1',
'created' => '2015-09-03 19:16:55',
'modified' => '2015-09-03 19:16:55'
),
(int) 1 => array(
'id' => '55e8809e-d018-4ebe-a4cf-fbef72b40463',
'site_page_id' => '55e88078-16c8-46ce-bf02-fa5372b40463',
'name' => 'group-2',
'friendly_name' => 'Group 2',
'order' => '2',
'created' => '2015-09-03 19:17:18',
'modified' => '2015-09-03 19:17:18'
)
)
)
The way I am getting this result is by doing this
$sitePage = $this->SitePage->find('first', array(
'conditions' => array(
'SitePage.id' => $id,
),
));
unset($sitePage['SitePage']['id'], $sitePage['SitePageGroup']['id'], $sitePage['SitePageGroup']['SitePageContent']['id'], $sitePage['SitePageGroup']['site_page_id'], $sitePage['SitePageGroup']['SitePageContent']['site_page_group_id'] /* further ids */);
debug($sitePage);
die();
But also also as you can see in the debug output the 3rd level of associated models are not being included, each of the SitePageGroup should also have a SitePageContent
I think a simple loop over the array of SitePageGroup should reset the id's and set the foreign keys to null, but I guess I also need to somehow include the SitePageContent that belongs to the SitePageGroup so I can reset those as well.
You need to ensure that all primary and foreign keys are set to null before saving. You only appear to be resetting the primary keys of your models but Cake needs to know that the foreign keys need generating so that they reference the new records.
Before calling $record it might be worth using debug($record); to check that everything in that array has been set/reset appropriately to ensure the copy will work as expected.
Update
Based on the array contents you've posted in your updated question it appears that you are not removing all the primary and foreign keys from your save data. You need to make sure that these are removed from everything you are about to save including the has many associations.
If you look at your array you should be able to see that unset($sitePage['SitePageGroup']['id']) will not remove the primary IDs of your SitePageGroup data as what you are unsetting doesn't correspond to array paths in your $sitePage array.
You can use CakePHP's Hash utility to remove the primary keys from the array like this:-
$sitePage = Hash::remove($sitePage, 'SitePageGroup.{n}.id');
And similarly for the foreign keys:-
$sitePage = Hash::remove($sitePage, 'SitePageGroup.{n}.site_page_id');
I have a hasmany relationship between Guardian ans Student. A Guardian hasmany Students. I cant get the required fields from containable object students, instead I get everything from Students but I do get the required fields from Guardian.
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
$this->Guardian->Behaviors->load('Containable');
$guardians =$this->Guardian->find('all',array(
'contain'=>array('Student',
array( 'fields'=> array('Student.guardian_id,Student.id,Student.first_name' ))),
'order' => array('guardian_first_name ASC'),
'fields'=> array('Guardian.guardian_first_name,Guardian.guardian_last_name,Guardian.id' ),
'recursive'=> -1
));
array(
(int) 0 => array(
'Guardian' => array(
'guardian_first_name' => '',
'guardian_last_name' => '',
'id' => '166'
),
'Student' => array(
(int) 0 => array(
'id' => '166',
'student_inactive' => true,
'student_enq' => false,
'student_unallocated' => false,
'first_name' => 'Kala',
'last_name' => 'narayanan',
The fields option is not nested correctly, which you maybe would have noticed if you'd format your code properly, something along the lines of this:
$this->Guardian->Behaviors->load('Containable');
$guardians = $this->Guardian->find('all', array(
'contain' => array(
'Student',
array(
'fields'=> array(
'Student.guardian_id,Student.id,Student.first_name'
)
)
),
'order' => array(
'guardian_first_name ASC'
),
'fields' => array(
'Guardian.guardian_first_name,Guardian.guardian_last_name,Guardian.id'
),
'recursive'=> -1
));
The array holding the fields option must be passed as the value for Student key.
// ...
'contain' => array(
'Student' => array(
'fields'=> /* ...*/
)
),
// ...
On a side note, when passing the fields as a comma separated string (which might not be the best idea), it's not necessary to pass them in an array.
array(
'fields'=> array(
guardian_id, id, first_name'
)
)
use fields without model name.
I have a model Ranking which holds a contact_id and belongsTo Model Contact.
Model Contact has a costumer_id and belongsTo Model Costumer.
And hasMany Rankings.
There is also a Model Product which hasMany Ranking.
On a statistics page I select
$this->Product->recursive = 1;
$this->set('products', $this->Paginator->paginate())
;
and I get the array of
array(
'Product' => array(
'id' => '69',
),
'Ranking' => array(
(int) 0 => array(
'id' => '29',
'contact_id' => '9',
'product_id' => '69',
'ranking' => '9',
),
I would like to bind now the Contact and Costumer to the ranking based on the contact_id.
Is this manually possible via bindModel?
If yes, how can I do that?
I tried to set $this->Product->recursive = 1; to 2 and 3, but that select so many other things which I would need to clear with unbindModel... So I hope there is a smarter way of bind those model to get to the data...?
What you basically want to use is containable behavior. With this behavior you are able to filter and limit model find operations. You have the possibility to add this behavior on model level or at the controller to avoid side effects if the application has already grown to a complicated level.
Example from Cake-Book:
// Activate Containable Behavior on the fly in a controller
$this->User->Behaviors->load('Containable');
$this->User->contain();
$this->User->find('all', array(
'contain' => array(
'Profile',
'Account' => array(
'AccountSummary'
),
'Post' => array(
'PostAttachment' => array(
'fields' => array('id', 'name'),
'PostAttachmentHistory' => array(
'HistoryNotes' => array(
'fields' => array('id', 'note')
)
)
),
'Tag' => array(
'conditions' => array('Tag.name LIKE' => '%happy%')
)
)
)
));
Hope this gives you a push into the right direction.
using find it will get me the right data with this:
$this->set('products', $this->Product->find('all', array(
'contain' => array(
'Ranking' => array(
'Contact' => array(
'foreignKey' => 'contact_id',
'Customer' => array(
'foreignKey' => 'customer_id',
)
)
)
)
)));
When using the Paginator it looks like
$this->Paginator->settings['contain'] = array(
'Ranking' => array(
'Contact' => array(
'foreignKey' => 'contact_id',
'Customer' => array(
'foreignKey' => 'customer_id',
)
)
)
);
$this->Product->Behaviors->load('Containable');
$this->set('products', $this->Paginator->paginate());
Thanks so much!!
I have associations:
Product -> hasMany -> ProductOption
Product -> hasMany -> ProductImage
I want to find the product data including ProductImage with the ProductOption.id
When I do this:
$this->Basket->Product->ProductOption->find('first',array(
'contain' => array(
'Product' => array(
'ProductOption' => array(
'conditions' => array('ProductOption.id = '.$id)
),
'ProductImage'
)
)
));
I get this:
array(
'ProductOption' => array(
'id' => '46',
'product_id' => '9',
),
'Product' => array(
'id' => '9',
'name' => 'Some product',
)
)
Which is most of what I want but without 'ProductImage' included. How do I get this in the array?
I think you're using too much recursion. If you're using Containable on Product, make the query on it, not ProductOption, like this:
$this->Basket->Product->find('first',array(
'contain' => array(
'ProductOption' => array(
'conditions' => array('ProductOption.id = '.$id)
),
'ProductImage'
)
));
And no need to use Product on 'contain' array, it's already guessed.
(I didn't try this, but almost sure)
This is one of those times when I know I'm doing something wrong, but I'm apparently deaf, dumb and blind with respect to seeing it. I'm hoping that another pair of eyes can open my own.
I have a ZipCode model and an Incentive model. There is a glorified join table (glorified because it has its own key) sitting in the middle. The join table has id, incentive_id and zip fields (legacy database). My ZipCode model HABTM Incentive as shown:
public $hasAndBelongsToMany = array(
'Incentive' => array(
'with' => 'ZipCodeIncentive',
'foreignKey' => 'zip',
'associationForeignKey' => 'incentive_id',
),
);
My Incentive model HABTM ZipCode as follows:
public $hasAndBelongsToMany = array(
'ZipCode' => array(
'with' => 'ZipCodeIncentive',
'foreignKey' => 'incentive_id',
'associationForeignKey' => 'zip',
),
I have a method, ZipCode::incentives( $zip ) that wants to pull all of the incentives relevant to the specified zip code:
$incentives = $this->Incentive->find(
'all',
array(
'contain' => array( 'ZipCode' ),
'fields' => array( 'Incentive.id', 'Incentive.name', 'Incentive.it_name', 'Incentive.amount', 'Incentive.state', 'Incentive.entire_state', 'Incentive.excluded', 'Incentive.is_active' ),
'conditions' => array(
'Incentive.excluded' => 0,
'Incentive.is_active' => 1,
'OR' => array(
'Incentive.state' => 'US', # nationwide incentives
array(
# Incentives that apply to the entire state the zip code belongs to
'Incentive.entire_state' => 1,
'Incentive.state' => $state,
),
'ZipCode.zip' => $zip # specific to the building's zip code
)
),
'order' => array( 'Incentive.amount DESC' ),
)
);
What I get for my trouble is the following error:
SQL Error: 1054: Unknown column 'ZipCode.zip' in 'where clause'
The ZipCode model's table isn't getting joined in the SQL, but I haven't grasped why yet. It's worth mentioning that the Incentive model is tied to a MySql view, not a table, via $useTable. I haven't seen anything to suggest that it should be a problem in this scenario, but it's non-standard.
If you see what I'm missing, please call 911 or at least drop an answer.
Rob
Move the condition
'ZipCode.zip' => $zip
To your contain declaration like this
array(
'contain' => array( 'ZipCode'=>
array('conditions'=>
array('ZipCode.zip' => $zip ))),
Then continue with the rest of your statement as usual