m0g
m0g

Reputation: 115

PHP/CakePHP : Relation HasOneBelongToOne

I'm trying to figured out what's the best way to make a "Has One Belong to One" relation in CakePHP. Unfortunatly I didn't found anything for helping me on the internet.

I've tried to proceed like that:

Company model :

var $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

User model :

var $hasOne = array(
    'Company' => array(
        'className'    => 'Company',
        //'foreignKey' => 'user_id',
        'dependent'    => true
    )
);

But still cakePHP allow me to create two companies for one user.

And here my database schema : Company : id, name, ..., user_id User : id, name, ...

Many thanks

Upvotes: 0

Views: 127

Answers (3)

user1012851
user1012851

Reputation:

In your database, company table, user_id should be set unique.

Upvotes: 0

petervaz
petervaz

Reputation: 14205

If each user has only one company and each company belongs to one and only one user, shouldn't they be on the same table?

like:

USER
Id
Name
...
Company

Sorry if I shouldn't ask questions back here but seemed pertinent.

Upvotes: 0

Matyas
Matyas

Reputation: 13712

CakePHP can handle the following relationships only:

  • one to one
  • one to many
  • many to one
  • many to many

Read more here

If you want to do "Has One Belong to One" then use the hasOne feature in both objects.

Upvotes: 3

Related Questions