CakePHP automatically remove associated items - database

this may be a rookie question for CakePHP but here it goes
I design 3 models with associations:
'Client' hasMany 'Invoice' hasMany 'Item'
So when we do a read from Client, it will automatically grab related Invoices.
What if we try to delete a Client, is there a way so that CakePHP will automatically delete all related entries in 'Invoice' and subsequently all related entries in 'Item' ?

Yes, if the association is declared as dependent.
See http://book.cakephp.org/view/1043/hasMany.

Related

One Way One-To-One Association in CakePHP

I have an idea of how to do this but it doesn't seem like proper convention. I have a Submission model and a Revision model each with their similarly named tables. Each Submission can have one or more Revisions associated to it in a $hasMany relationship. The Revision model hence has a $belongsTo relationship linking back to the Submission.
In addition to having this relationship, the Submission model needs to have another association (called activeRevision) to a particular Revision in a $hasOne style of relationship. However, the $hasOne type requires the foreign key to be in the Revision table. I want it to be in the Submission table, so I don't need to query all of the Submission's Revisions to find the active one. I realized just specifying a $belongsTo relationship in the Submission would do what I want, but this feels wrong to me as now the two models "belong to eachother".
Is there a better way to go about this?
I wouldn't worry too much because of the 'naming' of the relation. By having the foreign key of the Revision inside the Submission table, CakePHP is, in fact, right that you've created a 'belongsTo' relation.
Although not strictly the 'right' (?) relation, in this situation, this looks like it's an easy way to achieve what you want. Just be sure to add an additional condition to your relation to prevent that a revision of another submission can be set as the current revision, i.e.;
public $belongsTo = array(
'Revision' => array(
'conditions' => array(
'Revision.submission_id = Submission.id',
)
)
);
However, make sure to add a proper comment in your code to prevent confusion if you're (or somebody else is) looking at your code in a later stage. (e.g. "note: using belongsTo relation, because its easier to maintain)
If you really want to convert it to a hasOne relation, you'll have to add an additional column to the 'Revisions' table, for example 'is_curreny_revision'. However, you will also need to be sure that only one revision of a submission can be set to be the current revision.
If you're using PostgreSQL, this can be achieved using a 'partial unique' index (see this question on StackOverflow; PostgreSQL: Conditional unique constraint). MySQL does not support partial indexes, so you're out of luck there

CakePHP Models with associated conditions

I have three models that are as follows:
Location hasMany SportType hasMany Sport, then
Sport belongsTo SportType belongsTo Location
In the SportType model, the belongsTo Location has a condition 'Location.status' => true, such that it only retrieves records where the Location status is true. Works fine.
When retrieving records via a plain old find() in the Sport model, I would assume that it would not return records where the associated SportType's associated Location was false, but that is not the case.
I believe I could use containable behavior or explicitly constructed joins in my controller to get what I want, but I'm wondering if this is something I can achieve purely through the model relationships. Perhaps not.
You can either use Joins or change the model you're doing the search on and do it through the restricting model (ie Location).
$this->Location->find('all', array(
'conditions' => array(
'Location.status' => true
),
'contain' => array(
'SportType' => array(
'Sport'
)
)
));
But you cannot narrow the results of the searching model based on conditions within contained models.
Update:
Joins also allow you to add more conditions to other models...etc, as opposed to Contain which does not, so I supposed I'd lean toward going with Joins as that leaves you more flexibility moving forward.
Also, a JOIN will do one more-complicated query, while a contain will do many simpler queries... so depending on your database structure, that could be considered.
Bottom line, it's preference - both are just fine and whichever works for you is great.

Is it possible to custom the delete on cascade of CakePHP?

I have a table with logs related to the Post ones and i dont want its data to be deleted when i delete a Post.
In the other hand, i want to delete all the comments of the Post as well as other data.
I have been taking a look at the documentation but they dont say anything about it:
http://book.cakephp.org/2.0/en/models/deleting-data.html
Thanks.
You can do this in at least two different ways.
On is when you're calling $this->Post->delete($id, $cascade) the second parameter is a boolean that shows if the delete operation should also remove any associated records - such that depend on a Post record:
$this->Post->delete($id, false);
Will not delete any associated records. This is also true for $this->Model->deleteAll();This is when you want to set it not globally.
Depends is very important because this concept could also be set in the configuration of a hasMany or hasOne relation so that this is the default deletion behaveour:
public $hasMany = array(
'Log' => array(
'className' => 'Log',
'foreignKey' => 'post_id',
'dependent' => false
)
);
In this example, Log records will NOT be deleted when their associated Post record has been deleted.
You can try removing the association before calling the delete using $this->Post->unbindModel('hasMany' => 'Log') (or $this->unbindModel('hasMany' => 'Log'inside Post model.)
If your back end is MySQL, you can switch off foreign key checks (SET FOREIGN_KEY_CHECKS=0;), remove the parent Post and its comments, and re-enable foreign key checks (SET FOREIGN_KEY_CHECKS=1;). I don't recommend this however.
I'd be inclined to implement a 'soft delete' on posts (give it a 'deleted' field and add an index to it which you set to true when it's deleted) and update your front end queries to ignore any posts with deleted = 1
There are a few soft delete behaviors out there but the code is pretty simple to implement.

How extensive is an Object in CakePHP model linkage?

I was hoping someone with an understanding on CakePHP could shed some light on a question I've been having.
Here's my scenario, I have a User this User has a Company which in turn has many Department and many Address. If I were to get a User could I expect to have access to the Company and all models associated with that Company?
So would $user['Company']['Department'][0] or $user['Company']['Address'][0] be possible?
Which brings me back to the original question, how extensive is the linkage between models?
In plain-vanilla model, Cake's model linkage is determined by your models' recursive attribute. Your example model relationship looks something like this:
User
-> belongsTo Company
-> hasMany Department
-> hasMany Address
-> hasMany PhoneExtension
(I've added an additional relationship (User hasMany PhoneExtension) to flesh out the following explanation.)
There are three accepted values for Model::recursive: -1, 0, 1 and 2. Each value indicates to Cake's ORM a different depth to retrieve model records. I'll use $this->User->find('all') to illustrate the difference.
At recursive = -1, Cake retrieves only the specified model (ie. User). It parses none of the model associations.
At recursive = 0, Cake retrieves the specified model, and parses its belongsTo associations. $this->User->find('all') would retrieve all User records, as well as the Company record to which each User belongs.
At recursive = 1, Cake retrieves the specified model, and parses all of its direct associations. $this->User->find('all') would retrieve all User records, as well as the Company record to which each User belongs, and all PhoneExtension records belonging to the User.
At recursive = 2, Cake retrieves the specified model, parses all of its direct associations and all associations of its direct associations. $this->User->find('all') would retrieve everything in the example model relationship diagram: all User records, the Company records to which the User records belong, all PhoneExtension records belonging to the User, and all Department and Address records belonging to the Company.
Which is the very long way of saying that yes, you can achieve the results you indicate in your question, at recursive = 2.
If you wanted to go deeper than what recursive = 2 gets you, you'll have to use the Containable behaviour. Let's say that your Department model had an additional association: hasMany Group. Thus:
User
-> belongsTo Company
-> hasMany Department
-> hasMany Group
-> hasMany Address
-> hasMany PhoneExtension
To retrieve everything we got with a recursive = 2 retrieval, as well as all the associated Group records, you'd construct your Model::find call like this:
$this->User->find('all', array(
'contain' => array(
'PhoneExtension',
'Company' => array(
'Department' => array( 'Group' ),
'Address'
)
)
));
It's as extensive as you need/want it to be. Look into the recursive option of the find() family of methods. Also the Containable behavior. The specific references you list are possible, but directly under the user:
$user['Department'][0]
Think of it as the user having many departments through its company.
If you access a class/object and set "$this->recursive = -1" then it only returns the object without the dependencies!

CakePHP hasAndBelongsToMany (HABTM) Delete Joining Record

I have a HABTM relationship between Users and Locations. Both Models have the appropriate $hasAndBelongsToMany variable set.
When I managing User Locations, I want to delete the association between the User and Location, but not the Location. Clearly this Location could belong to other users. I would expect the following code to delete just the join table record provided the HABTM associations, but it deleted both records.
$this->Weather->deleteAll(array('Weather.id' => $this->data['weather_ids'], false);
However, I am new to CakePHP, so I am sure I am missing something. I have tried setting cascade to false and changing the Model order with User, User->Weather, Weather->User. No luck.
Thanks in advance for any help.
Not quite sure how Weather is related to your models, so I'll just go with the traditional names, LocationsUser is the joining table. This should delete all associations between the user with id $id and any locations:
$this->User->LocationsUser->deleteAll(array('LocationsUser.user_id' => $id), false);
Notice also that you're missing a closing bracket in your code snippet.

Resources