I feel pretty darn dumb for asking this question but I'm baffled, probably because I'm slightly intimidated with cakePHP(new to it, and not very comfortable),but its merits are practically forcing me to use it. So please if you could help, I appreciate it :
My problem is with understanding how Model association works. After going through all the section about associations here I am still struggling and actually am not quite sure whether either my database design is flawed, or the associations between the models, are wrong.
Here it is : I have 3 Models, which are : Donor, BloodGroup, DonorType
To start with, I am not completely sure if I should create a model for every table in the db. My tables look like this :
+-------donors-------+
| donor_id (pk) |
| name |
| surname |
| donor_type_id (fk) |
| blood_group_id (fk)|
| |
+--------------------+
+----donor_types-----+
| type_id (pk) |
| type |
| |
+--------------------+
+----blood_groups----+
| blood_group_id(pk) |
| group |
| |
+--------------------+
Donor Model
class Donor extends AppModel{
public $hasOne = array(
'BloodGroup'=> array(
'className' => 'BloodGroup'
),
'DonorType' => array(
'className' => 'DonorType'
)
);
According to the tables in the database, above is how the relationships can be described. I am already using the association to register a new donor with values retrieved from the blood group table/model, using this code in my controller:
$this->set('bloodGroups', $this->Donor->BloodGroup->find('list', array('fields' => array( 'BloodGroup.blood_group_id','BloodGroup.blood_group' ) ) ));
Therefore I think the association is correct. However, now I want to display the stored users with the relevant details, but an sql error is being generated :
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'BloodGroup.donor_id' in 'on clause'
This is ofcourse because there is no 'donor_id' as a fk inside the BloodGroup table, by actually there is a blood_group_id as a fk inside the donor table. So what is the solution to this? Is the db design flawed or is there a way I can redefine the association within cake ?
There appear to be 2 things wrong with your setup.
id
, nottable_name_id
. Cake always looks forid
keys by default. If you have no choice, you can set a custom primary key by setting the primaryKey property in your model.This is also illustrated with some examples in the documentation (see links above). The latter one is true in your case, so your model should eventually look like this: