CakePHP HABTM: Editing one item casuses HABTM row to get recreated, destroys extra data - cakephp

I'm having trouble with my HABTM relationship in CakePHP.
I have two models like so: Department HABTM Location. One large company has many buildings, and each building provides a limited number of services. Each building also has its own webpage, so in addition to the HABTM relationship itself, each HABTM row also has a url field where the user can visit to find additional information about the service they're interested and how it operates at the building they're interested in.
I've set up the models like so:
<?php
class Location extends AppModel {
var $name = 'Location';
var $hasAndBelongsToMany = array(
'Department' => array(
'with' => 'DepartmentsLocation',
'unique' => true
)
);
}
?>
<?php
class Department extends AppModel {
var $name = 'Department';
var $hasAndBelongsToMany = array(
'Location' => array(
'with' => 'DepartmentsLocation',
'unique' => true
)
);
}
?>
<?php
class DepartmentsLocation extends AppModel {
var $name = 'DepartmentsLocation';
var $belongsTo = array(
'Department',
'Location'
);
// I'm pretty sure this method is unrelated. It's not being called when this error
// occurs. Its purpose is to prevent having two HABTM rows with the same location
// and department.
function beforeSave() {
// kill any existing rows with same associations
$this->log(__FILE__ . ": killing existing HABTM rows", LOG_DEBUG);
$result = $this->find('all', array("conditions" =>
array("location_id" => $this->data['DepartmentsLocation']['location_id'],
"department_id" => $this->data['DepartmentsLocation']['department_id'])));
foreach($result as $row) {
$this->delete($row['DepartmentsLocation']['id']);
}
return true;
}
}
?>
The controllers are completely uninteresting.
The problem:
If I edit the name of a Location, all of the DepartmentsLocations that were linked to that Location are re-created with empty URLs. Since the models specify that unique is true, this also causes all of the newer rows to overwrite the older rows, which essentially destroys all of the URLs.
I would like to know two things:
Can I stop this? If so, how?
And, on a less technical and more whiney note: Why does this even happen? It seems bizarre to me that editing a field through Cake should cause so much trouble, when I can easily go through phpMyAdmin, edit the Location name there, and get exactly the result I would expect. Why does CakePHP touch the HABTM data when I'm just editing a field on a row? It's not even a foreign key!

From the CookBook the 1st problem is:
By default when saving a
HasAndBelongsToMany relationship, Cake
will delete all rows on the join table
before saving new ones.
I am not quite sure why Cake is trying to save the HABTM data even though you don't have a foreign key in your data, but there is an easy solution for that. Simply destroy the association for the save call:
$this->Location->unbindModel(
array('hasAndBelongsToMany' => array('Department'))
);

I'm thinking of one reason why this might be happening. When you retrieve Location, you also retrieve locations_departments data. And when you do a save($this->data) it looks for models in the array and saves them.
A way to solve this is setting the recursive attribute (of a model) to -1 or 0 (try, I'm not sure, just print out the data to see what comes out). You can set it in the model: var $recursive = -1; or in the controller method (action): $this->ModelName->recursive = -1;
More about recursive: http://book.cakephp.org/view/439/recursive
It's really similar to what harpax suggested, just if you don't need that data, tell it to Cake, so that it won't fetch it.

Trouble is that when saving your Location, you gave the save method an array containing all the DepartmentsLocations too. Thus CakePHP destroys everything and try to recreate it.
This is a common mistake with cake since it will often pull far too many results for you.
Be sure to pass only the data that needs to be saved, or better to fetch only the datas you need.

Related

What is the wrong here on associaction cake php

I am working on cake php and I have an association with users and user_details table, When I sign up then its working fine. Its post data on both the tables but when I redirect to profile page then it throws an error of userDetail array. When I printed that info array I got only one array instead of two arrays one is User and another one is UserDetail. Its working fine on my local machine but not working on server, But when I used recursive=>1 than its works. Please let me know what wrong here.
Query
$userInfo = $this->User->find('first',array('conditions'=>array('User.id'=>$userId)));
when I pass recursive than it works
$userInfo = $this->User->find('first',array('recursive'=>1,'conditions'=>array('User.id'=>$userId)));
Thanks
Shiv
Please use Containable behavior. It's more intuitive and clean then recursive variable. You can do this adding in your AppModel (or specific models if you don't want this behavior in all of them):
public $actsAs = array('Containable');
Then, in your find:
$userInfo = $this->User->find('first',array(
'conditions'=>array(
'User.id'=> $userId
),
'contain' => array('UserDetail')
));
If you have declared your association, you will retrieve your User along any UserDetail for that User
If you always want UserDetail to be fetched when you do a find on User, add the $recursive property to your User model:
public $recursive = 1;
However, the above is not recommended as usually, $recursive should be set to -1 in your AppModel. This is because Model::find() should normally only fetch data from a single model and not ALL related models. E.g. if your User model is related to say UserDetail and UserRole model, data from all of them will be fetched if $recursive is not equal to -1. This slows down your app.
When you do require related model data like in your question, use the containable behavior like this:
$userInfo = $this->User->find('first', array(
'conditions' => array('User.id'=>$userId),
'contain' => array('UserDetail')
));

How to get the model that initiates a saveAll call in the related model

Is it possible to get the Model that is trying to save data to a related model in a saveAll transaction. If forexample, User hasMany Goal, and I make a call;
$this->User->saveAll($data);
Can I get the Model User in the Goal Model class using some predefined attritbute, method or mechanism?
Thanks for your help in advance,
Roland.
Edit:
Assume a hypothetical situation where a user has pictures, with a Picture model and Posts( blogs) with a corresponding model. These both can be commented upon. So rather than creating a separate comment model for each of these models, I create one central Comment model. The association might look like this;
//In the Picture model
var $hasMany = array(
`` 'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'picture_id',
'conditions' => array('Comment.objectType' => 'picture')
)`
);
The association for the Post model will be similar, the only difference being;
'conditions' => array('Comment.objectType' => 'post')
With this structure, if I were to query any of these Models, their corresponding comments will be retrieved from the DB table using the objectType field.
If I were to do something like;
$this->Picture->saveAll($data);
, or
$this->Post->saveAll($data);
with the $data array well structured and containing a Comments part to be saved, at some point in time during the saving transaction, data will be saved to the comments table through the Comment model.
What I want is to be able to know that it is the Picture model trying to save comment in the Comment model's beforeSave method, i.e;
//In the Comment mode
beforeSave() {
//Post model is trying to save a comment here
}
With CakePHP, if you associate your models using the hasMany, while you are in the controller you can access that model.
In UserModel
var $hasMany = array('Goal');
In GoalModel
function myCrazyFunc() {
//crazy stuff happens here
}
In UsersController
$this->Goal->myCrazyFunc();
//more stuff
$this->User->saveAll($data);

cakePHP hasOne relationship not auto completing dropdown field

I'm trying to implement a hasone relationship between 2 models, but I can't have the 'add' form autocomplete with the possible options in the second model (the one that belongsTo the first one). This is my code:
- model 1: item.php
<?php
class Item extends AppModel{
var $name = 'Item';
var $primaryKey = 'id';
var $hasOne = 'CoverImage';
}
?>
- model 2: cover_image.php
<?php
class CoverImage extends AppModel{
var $name = 'CoverImage';
var $primaryKey = 'id';
var $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'item_id'
));
}
?>
- add view of model 2: add.ctp
<?php echo $this->Form->create('CoverImage',array('url' => array('controller' => 'admins', 'action' => 'add')));?>
<fieldset>
<legend><?php __('Info'); ?></legend>
<?php
echo $this->Form->input('item_id');
echo $this->Form->input('description');
?>
</fieldset>
<?php echo $this->Form->end(__('Create', true));?>
For what I see in Cake's documentation, with this relationship, in the add view I should see a dropdown list in the item_id field to be able to select to which item does this CoverImage belongs to, but the dropdown is empty (and yes, I have some items in the items table already).
Maybe I'm missing something or I've done something wrong, but I can't figure it out. Thanks so much in advance for any clues!
EDIT
One think I've just realized is that if I do this:
echo $this->Form->input('item_id', array('type'=>'text'));
instead of this:
echo $this->Form->input('item_id');
I can add/edit the *item_id* field, I can see its value in the text box. However, if I leave the other one, I just see an empty dropbox and when I try to add/edit a CoverImage, it doesn't work, it just shows an empty white page, not even with errors...
Maybe this is a lead to something...
In order for that to work you have to create a list of possible options in the controller. That does not happen automatically.
public function add() {
$items = $this->CoverImage->Item->find('list');
$this->set(compact('items'));
}
The FormHelper only automatically infers that the field item_id should be populated by the options in the variable $items (plural, no _id).
Do be careful that Items that already haveOne CoverImage should not be part of that list. find('list', array('conditions' => array('CoverItem.id' => null))) will probably* take care of that, but you'll need to recheck just before saving as well, or you need to rethink your associations.
* Not sure off the top of my head whether that'll work for 'list' searches.
EXCELLENT QUESTION. You've run afoul of a disingenuous feature of Cake's associations:
Considering you defined the relationship as hasOne? Guessing at the trace but Cake probably even correctly inferred your preference for list functionality. You got your automagic list...
...of One.
$hasOne is pretty exclusive like that. It "uses up" those "has" relationships (it's makes the relationship a de facto Singleton - so Users only have 1 Profile <-> Profile only has 1 User). Consider - Database can have many configurations, but Dbo will only ever have one Connection at a time and Connection will only have one Dbo. Thus -> hasOne is for marrying two Models til die() do they part.
-- So it doesn't get used nearly as much as hasMany and belongsTo.
For your purpose, you probably want to change to a different association.
Adding an additional $this->Item->find doesn't really fix what's wrong (and I wouldn't recommend it, unless you're mostly done with both models/controllers, or you actively want things to start getting weird fast.)
Also, changing how you call the Form Helper methods - if you return a 'list' type fetch from a find, Cake will automatically produce an option list out of it. What's actually happening is, you're sneaking around your Model on a very thin margin of View functionality. That's why specifying the input type to "break the magic" tends to be discouraged (which, you totally can if you want. Just understand what's actually happening, or: see, weird, fast.)
But you might want to rethink how you've associated your models - wouldn't it also be correct to say, each Item belongsTo a CoverImage (same as each CoverImage belongs to an Item) -- because you have a form expressly permitting a CoverImage to select an Item, any Item, to be displayed with? You'll probably get better results.
HTH. :)

Cakephp Multiple Relations to the Same Model

I'm working on a real estate application, where one Home can be listed by either one or two Realtors. As such, I'm trying to follow the example given in section 3.7.6.7 of the Cake Cookbook. Here's what's going on in my Realtors model:
class Realtor extends AppModel {
var $primaryKey = $num;
var $name = 'Realtor';
var $hasMany = array('Homes' =>
array('className' => 'Home',
'foreignKey' => 'realtor_num',
...),
'CoListedHomes' =>
array('className' => 'Home',
'foreignKey' => 'realtor2_num',
...)
);
This completely breaks the application, with the error message "Database table co_listed_homes for model CoListedHomes was not found."
Referring back to the Cookbook 3.7.6.7, second example, it seems clear that they shouldn't have or need separate "messages_received" and "messages_sent" tables in their database, so what is it that I'm doing wrong?
ETA: Weirdly (to me) I think I got the relationships to work by swapping around the order of the arrays: the first array, on foreignKey = realtor2_num, is called 'ListedHomes', the second array, on foreignKey = realtor_num is called 'Home'. I suppose my question then is, why should the order matter, and why should Cake started talking about unfound database tables in some circumstances?
Just in case, I'd have built this as a categories setup. Then created a join table between Category and Home.
Then you can have a hasAndBelongsToMany beween both categories and homes
"Database table co_listed_homes for model CoListedHomes was not found" probably refers to you not having a model defined for CoListedHomes that points to the homes table.
I would, however, code this as a n:m otherwise known as hasAndBelongsToMany, as stated by DavidYell.

CakePHP: Can I ignore a field when reading the Model from the DB?

In one of my models, I have a "LONGTEXT" field that has a big dump of a bunch of stuff that I never care to read, and it slows things down, since I'm moving much more data between the DB and the web app.
Is there a way to specify in the model that I want CakePHP to simply ignore that field, and never read it or do anything with it?
I really want to avoid the hassle of creating a separate table and a separate model, only for this field.
Thanks!
Daniel
As #SpawnCxy said, you'll need to use the 'fields' => array(...) option in a find to limit the data you want to retrieve. If you don't want to do this every time you write a find, you can add something like this to your models beforeFind() callback, which will automatically populate the fields options with all fields except the longtext field:
function beforeFind($query) {
if (!isset($query['fields'])) {
foreach ($this->_schema as $field => $foo) {
if ($field == 'longtextfield') {
continue;
}
$query['fields'][] = $this->alias . '.' . $field;
}
}
return $query;
}
Regarding comment:
That's true… The easiest way in this case is probably to unset the field from the schema.
unset($this->Model->_schema['longtextfield']);
I haven't tested it, but this should prevent the field from being included in the query. If you want to make this switchable for each query, you could move it to another variable like $Model->_schemaInactiveFields and move it back when needed. You could even make a Behavior for this.
The parameter fields may help you.It doesn't ignore fields but specifies fields you want:
array(
'conditions' => array('Model.field' => $thisValue), //array of conditions
'fields' => array('Model.field1', 'Model.field2'), //list columns you want
)
You can get more information of retrieving data in the cookbook .
Another idea:
Define your special query in the model:
function myfind($type,$params)
{
$params['fields'] = array('Model.field1','Model.field2',...);
return $this->find($type,$params);
}
Then use it in the controller
$this->Model->myfind($type,$params);
Also try containable behaviour will strip out all unwanted fields and works on model associations as well.
Containable
class Post extends AppModel { <br>
var $actsAs = array('Containable'); <br>
}
where Post is your model?
You can add a beforeFilter function in your Table and add a select to the query
Excample:
public function beforeFind(Event $event, Query $query){
$protected = $this->newEntity()->hidden;
$tableSchema = $event->subject()->schema();
$fields = $tableSchema->columns();
foreach($fields as $key => $name){
if(in_array($name,$protected)){
unset($fields[$key]);
}
}
$query->select($fields);
return $event;
}
In this excample I took the hidden fields from the ModelClass to exclude from result.
Took it from my answer to a simular question here : Hidden fields are still listed from database in cakephp 3

Resources