CakePHP Models with associated conditions - cakephp

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.

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 Associations, Containable, and Threaded

Hi I've got a couple of questions regarding associations and how they play in cases
of complex find() calls.
If I've got a model Post and a model Comment with the latter having a parent_id field
and I want to fetch a post with its associated comments threaded, do I simply perform a
find('threaded', ...) on Post itself or will this result in an error because Post doesn't
have a parent_id? I am particularly concerned about a Containable + Threaded find. (the
example I give here is a simplified version of what I actually need to implement)
What is the significance of Association Names? Does Containable work on association names
or model names? (the reason I want to know this is because I'm trying to implement polymorphic models by having condition-specific model associations, often having multiple associations to the same model)
I think that containable would not support threaded finds on the contained models. EG you might have a post_id column in your comments table, and do something like:
$this->Comment->find('threaded', array(
'conditions' => array(
'post_id' => 5)));
Although the book may say that Containable uses the model name, I have regularly used the association name in Containable when I have multiple joins between the same models. For simple projects, the model name is usually the same as the association name, so that may be why the book says that.

CakePHP : Multiple hasOne Model Relations

I'm trying to create an application which should help distribute work to employees or volunteers on a irregular time schedule based on their availabilities.
Anyway, here are my models and the relations between them :
Users hasMany Jobs
Jobs belongTo Users
Users hasMany Availabilities
Availabilities belongTo Users
Jobs hasOne Periods
Periods belongTo Jobs
Availabilities hasOne Periods
Periods belongTo Availabilities
The problem is that "Periods" is on the receiving side of two hasOne relationships and, if I'm not wrong, it's something you can't do in CakePHP. What is the best way to proceed in this situation?
You might have also spotted the fact a "Job" may be assigned to someone (a "User") or not. Should I drop the relationship and create it once the job has been assigned or should I create a fictional user representing "nobody" for unassigned jobs?
I would have posted a nice image but i don't have enough reputation, sorry!
Here's a link though.
The problem is that "Periods" is on the receiving side of two hasOne relationships and, if I'm not wrong, it's something you can't do in CakePHP. What is the best way to proceed in this situation?
I don't see a problem. You should be able to add the foreign key for each hasOne relationship to the periods table (periods.job_id and periods.availability_id).
You might have also spotted the fact a "Job" may be assigned to someone (a "User") or not. Should I drop the relationship and create it once the job has been assigned or should I create a fictional user representing "nobody" for unassigned jobs?
This is fine. Just set the jobs.user_id to allow null values and set up the relationship. This will allow jobs to be created without being assigned to users. After you perform a find you can check empty($results['User']) to determine if you are dealing with an unassigned job.
Users hasMany Jobs, Jobs belongTo Users, ...
Just a reminder: model names should be singular (ie. User hasMany Job, Job belongsTo User, etc.)
Also I'd like a Period to belong to either a Job or an Availability and never both at the same time. Is there a conventional way to do it?
You can write validation for that in the Period model:
$validate = array(
'job_id' => array(
array(
'rule' => 'validBelongsTo',
'message' => 'A period can either belong to a job or an availability'
),
),
);
public function validBelongsTo() {
$hasJob = !empty($this->data['Period']['job_id']);
$hasAvailability = !empty($this->data['Period']['availability_id']);
if ($hasJob && $hasAvailability) {
return false;
} else {
return true;
}
}
Sounds to me like the Period model should be polymorphic. Check out the answer to this question and this article in the bakery.
I used this technique frequently and it works beautifully for this kind of thing.

CakePHP automatically remove associated items

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.

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!

Resources