Friday, December 30, 2011

Re: CakePHP and a normalized database

Hi, the following should help (for v1.3)

It joins the User to the Person and then to the Address.. linking the rest of the tables should be similar.

<?php

class User extends AppModel {
var $name = 'User';

var $hasOne = array(
'Person' => array(
'className' => 'Person',
'foreignKey' => 'id',
'dependent' => true,
),
'Address' => array(
'className' => 'Address',
'foreignKey' => false,
'type' => 'LEFT',
'conditions' => array('Address.id = Person.address_id')
)
);

}

?>

If you use the foreignKey option when trying to link in Address, it tries to match the User.id to the Address.id, hence why I've set the condition instead. I was hoping that you could do nested 'hasOne' options, but doesn't seem so..

Clint


> Quick question, I have the following normalized MySQL database with
> tables:
>
> Users
> - id
> - username
> - password
> - person_id
>
> People
> - id
> - firstname
> - lastname
> - address_id
> - email_id
>
> Addresses
> - id
> - address
> - city_id
> - state_id
> - country_id
> - zipcode_id
>
> Countries
> - id
> - country
>
> I have been having problems setting the correct cakephp Model
> relations between them. Actually, after reading the documentation I'm
> not really sure if it's even possible to have this kind of databas
> structure work with cakephp.
>
> So far this is what I have:
> Users - belongsTo/hasOne - People (person_id)
> People - belongsTo/hasOne - Addresses (address_id)
> Addresses - belongsTo/hasOne - Countries (country_id)
>
> So, when I use the User model how can I have cakephp return everything
> from the user's firstname, lastname, to the address including country
> and states?
> To make matters more difficult, how can I have cakePHP (using the
> FormHelper) insert an user account that has the firstname and lastname
> (this I already got working), and also the address, city, state and
> country (this I can't figure it out)?
>
> My issue is that the Countries table for example is related to the
> Address table but not to the People table directly nor the Users table
> directly.
>
> Any help or guidance would be truly appreciated.
>
> Thanks in advance.
>
> --
> Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
> Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
>
>
> To unsubscribe from this group, send email to
> cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.


To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: