Link one model more than once - php

I have a function where a user can request a project. The request has 2 fields for other employees to be added.
It's got a field for a person who is responsible for the project (person_responsible) and the employee who is supposed to attend the opening meeting (person_attending).
What I want to know is, since both these fields (person_responsible and person_attending) will be pulling it's data from hr_employees table, how would I set this up in my Project-Model.
At the moment I have the one field set up like this:
public $belongsTo = array(
'HrEmployee' => array(
'className' => 'HrEmployee',
'foreignKey' => 'responsible_person',
'fields' => 'HrEmployee.employeename',
)
);
How would I set up the other field?

What I do in this cases is to make two associations. Since cake allow to customize relations, you can have two relations to the same model with different names.
public $belongsTo = array(
'ResponsibleEmployee' => array(
'className' => 'HrEmployee',
'foreignKey' => 'responsible_person',
'fields' => 'HrEmployee.employeename',
),
'AttendingEmployee' => array(
'className' => 'HrEmployee',
'foreignKey' => 'person_attending',
'fields' => 'HrEmployee.employeename',
)
);
Change the names to adjust your needs. Now, if your model is set as containable and you retrieve the Project model with those models in it, you'll get something like
array('Project' => array(/*data project*/),
'ResponsibleEmployee' => array(/*name*/),
'AttendingEmployee' => array(/*name*/)
)
(or another variation of that array depending on how the query was made).

Related

CakePHP- Retrieve deep associative data

I have an issue trying to retrieve associated model data from another associated model.
I have Donor Model which is associated with BloodGroup Model (belongsTo/hasMany rel).
Now, I also have a Donation Model which is associated with Donor Model (again, belongsTo/hasMany rel).
From the Donation Model, I want to retrieve data from the BloodGroup Model.
Currently only the Donor related data is retrieved. The idea is that I do not add a blood group field inside the donation, but map the blood group of a donation, on the fly, through the donor that made the donation!
I have been checking out the containable Behavior but I am not sure if this is how I can do it! It seems that it is used to 'contain' and filter data from associated models rather than to extend associations.
Any help appreciated very much, as always!
[EDIT]
DONOR MODEL
class Donor extends AppModel{
public $belongsTo = array(
'BloodGroup'=> array(
'className' => 'BloodGroup'
),
'DonorType' => array(
'className' => 'DonorType'
)
);
public $hasMany = array(
'Donation' => array(
'className' => 'Donation',
'foreignKey' => 'donor_id',
'order' => 'Donation.created DESC',
'limit' => 10,
'dependent' => true
)
);
DONATION MODEL
public $belongsTo = array(
'Donor' => array(
'className' => 'Donor',
'counterCache' => true,
)
);
From the Donation Controller :
public $paginate = array(
'order' => array("Donation.d_date" => 'desc'),
'limit' => 10
);
$this->Paginator->settings = $this->paginate;
$donations = $this->Paginator->paginate('Donation');
$this->set('donations',$donations)
Result retrieved :
[donations] => Array
(
[0] => Array
(
[Donation] => Array
(
[id] => 1
[donor_id] => 4
etc..
)
[Donor] => Array
(
[id] => 4
[name] => ...
)
)
)
It's not clear what data you actually want to get, but to answer what appears to be your hope:
"From the Donation Model, I want to retrieve data from the BloodGroup
Model."
Because there's a related path, you can get BloodGroup data, from the Donation model like this:
$this->Donor->BloodGroup->find('all');
Or by using Containable:
$this->find('all', array(
'contain' => array(
'Donor' => array(
'BloodGroup'
)
)
));
There's a lot of options - it just depends on what data you need.
For details on how I use find()s in my Model while still paginating, see this answer: https://stackoverflow.com/a/6577042/673664
(there are likely a lot of ways to do this - this is just the one I use, and works great for me)
If the BloodGroup has many Donor and if Donor has many Donation, You can retrieve Donation data from BloodGroup but you have to set the recursive to 2 ($this->Donation->recursive = 2;) before you use find method. If you want output blood group data from donation. Try that.

updating related tables in cake

I have this:
$this->request->data['Person']['person_id'] = $this->Session->read('insertedPersonID');
$savedPerson = $this->Person->saveAll($this->request->data, array('validate'=>'first'));
which updates the selected person row fine however its related tables like PersonColor and PersonParts are not updating, instead inserting new rows.
I thought cake automatically updates the related tables as well as long as the id of the main table which is the foreign key for the other two tables are provided since doing this:
$savedPerson = $this->Person->saveAll($this->request->data, array('validate'=>'first'));
inserts to the Person table and the other two related two tables fine.
How do I make it update the other two tables as well?
Edit:
For the model relations:
Person Model:
public $hasMany = array(
'PersonParts' => array(
'className' => 'Part',
'foreignKey' => 'part_person_id'
),
'PersonColors' => array(
'className' => 'Color',
'foreignKey' => 'color_person_id'
)
);
Part Model:
public $belongsTo = array(
'PartPerson' => array(
'className' => 'Person',
'foreignKey' => 'part_person_id'
)
);
Color Model:
public $belongsTo = array(
'ColorPerson' => array(
'className' => 'Person',
'foreignKey' => 'color_person_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
edit 2
var_dump of $this->request->data
array(3){
["Person"]=>array(4){
["person_user_id"]=>string(1)"3"
["person_name"]=>string(9)"Britney"
["person_category_id"]=>string(2)"16"
["visibility"]=>string(1)"1"
["person_id"]=>string(1)"71"
}
["PersonParts"]=>array(1){
[0]=>array(3){
["part_name"]=>string(4)"hands"
["quantity"]=>string(1)"2"
["part_part_type_id"]=>string(1)"1"
}
}
["PersonColors"]=>array(2){
[0]=>array(4){
["color_name"]=>string(3)"blue"
["test_field1"]=>string(1)"8"
["test_field2"]=>string(1)"9"
["position"]=>int(1)
}
[1]=>array(2){
["color_name"]=>string(5)"red"
["position"]=>int(2)
}
}
}
Note: This var_dump is only showing ["person_id"]=>string(1)"71" under Person array as the added field to make cake do an update, not insert... person_id is not showing under the PersonParts and PersonColors here since it's not working that way. What should I pass or How should I do an update on the other 2 related tables?
To make Cake do an update on the related tables, you do need to pass in the id of the related record, otherwise Cake won't know which record to update.
You can make this a hidden field in your form, which is how I do things.
The var dump for PersonParts should look like this (note the extra 'part_id' field):
["PersonParts"]=>array(1){
[0]=>array(3){
["part_id"]=>string(1)"7"
["part_name"]=>string(4)"hands"
["quantity"]=>string(1)"2"
["part_part_type_id"]=>string(1)"1"
}
}
If you don't pass the id, then (from memory) Cake will delete the existing related records, and add new ones.

Overriding a condition defined in an association in a find

I have a service where users are able to upload cars to the site, and select the manufacturer and model from a list. If the car model does not exist, the user can save a new model under the specific manufacturer.
Now to my problem, all models have to be confirmed by a moderator as being a valid type, having a correct spelling, and not being a duplicate etc. All confirmed models are visible to other users. I do this by specifying a condition in the Car's association as below:
$belongsTo = array(
'CarModel' => array(
'className' => 'CarModel',
'foreignKey' => 'car_model_id',
'conditions' => array('CarModel.confirmed' => 1),
'fields' => '',
'order' => ''
));
However, I want to override this condition in the edit action so that the user can see his models, even if they are not confirmed yet. Is that possible in the find conditions?
Regards,
Roland.
You can bind model before calling find() method. Try this in your action.
$this->ModelName->bindModel(
array('belongsTo' => array(
'CarModel' => array(
'className' => 'CarModel',
'conditions' => array('CarModel.confirmed' => 0), // Define your new condition here
)
)
)
);
$data = $this->ModelName->find('all'); // Now you will get the data for new condition applied
Hope it will work.

CakePHP/Croogo: A veeery complex association

When I was working on my current project, I ran into a rather complex issue. I'll point out my problem much more detailed right now:
There are three Models: User, UsersExtendedField and UsersExtended.
UsersExtendedField contains custom fields that can be managed manually. All custom fields can be shown in the Users view as well, and be filled out of course. The values are then stored in UsersExtended, which has got two foreignKeys: user_id and field_id.
The relations look like this: User hasMany UsersExtendedField, UsersExtendedField hasMany UsersExtended, UsersExtended belongsTo User, UsersExtendedField.
The problem: When accessing the Users view, a form with user information input is shown. Any UsersExtendedFields are available as well, and since these hasMany UsersExtended, they've got plenty of UsersExtended values. But I want to reduce those to only the value(s) that belong to the User, whose view is shown at the moment. Here are my (desired) relations:
Croogo::hookBehavior('User', 'Crooboard.ExtendedUser', array(
'relationship' => array(
'hasMany' => array(
'UsersExtendedField' => array(
'className' => 'Crooboard.UsersExtendedField',
'foreignKey' => '',
'conditions' => array('status' => 1)
),
),
),
));
class UsersExtendedField extends AppModel {
var $name = 'UsersExtendedField';
var $displayField = 'fieldname';
var $hasMany = array(
'UsersExtended' => array(
'className' => 'Crooboard.UsersExtended',
'foreignKey' => 'field_id',
'conditions' => array(
'UsersExtended.user_id = User.id'
)
),
);
}
This is not the full code, these are the important parts. The problem starts right where I wrote 'UsersExtended.user_id = User.id'. Obviously, this won't work. But I do not have any idea how to access the User.id here. I also could not imagine a HABTM structure to solve this task. Do you have any idea how to get the semantics of this 'UsersExtended.user_id = User.id' to work?
Thank your very much for taking the time to read through this and helping me!
It sounds like you need to set up your HABTM relationship properly.
You already have the join table, UsersExtended, which contains your foreign keys.
Remove all previous relationships and set up HABTM in each of your User and UserExtendedField models.
The relationship code in your User model would look like this:
var $hasAndBelongsToMany = array(
'UsersExtended' => array(
'className' => 'UsersExtended',
'joinTable' => 'UsersExtended', //assuming this is the
//name of that model's table
'foreignKey' => 'user_id',
'associationForeignKey' => 'field_id'
)
);
For more information check out the page in the cakephp book
In addition, this blog post helped me grasp the relationship concepts when I was learning cakephp.

CAKEPHP Stucked in Associating Models

Im using cakephp and Im stuck about the idea of listing multiple models, here's my scenario:
I have two major models namely Task and Events. I used the Events model to track all changes. this has the ff fields: id, model, model_id, changed
I used Events table to track multiple model changes. so when something changed to Task model it will be logged to Events models (get the idea??)
What I want to do is whenever i used the find method for Event model, i want to list the model information (for example, the Task model) together with my Events information like this:
array(
[0] => array (
[Event] => array(
id => 1
model => Task
model_id => 2
changed => array()
)
[Task] => array(
id => 2
name => Task 1
descp => Test Task
)
)
)
Note: The model can be any model, it can be Projects model.
At my task.php, it is no problem because i can easily declare:
var $hasMany = array(
'Events' => array(
'className' => 'Events',
'foreignKey' => 'model_id',
'dependent' => false,
'conditions' => array('Events.model' => 'Task')
)
);
I can get Events information using the find method on task although using
$this->Task->Event->find('all');
will not work, i dont know why.
So as soon as I declare, something like this in my Event Model:
var $belongsTo = array(
'Task' => array(
'className' => 'Task',
'foreignKey' => 'model_id',
'conditions' => array('Event.model' => 'Task', 'Event.model_id' => 'Task.id'),
'fields' => '',
'order' => ''
)
);
will throw an SQL error. Do you guys have an idea how to implement it??
Thanks in advanced. :)
I use polymorphic models all the time. The reason that $this->Task->Event->find('all') doesn't work is that you were performing the find on the Event model which, until you defined its belongsTo association, didn't have any means of retrieving the Task info.
As for now, the only thing I see that looks odd is that you've aliased your Task association as Events (plural) rather than its singular version which is the convention for models. You also identified the className as the plural version.

Categories