views:

157

answers:

3

Whats the usage of creation relations like

 var $belongsTo = array(
        'UserType' => array(
            'className' => 'UserType',
            'foreignKey' => 'user_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    var $hasMany = array(
        'UserOpenid' => array(
            'className' => 'UserOpenid',
            'foreignKey' => 'user_id',
            'dependent' => true)
);

What if i added a table which created in the sense of "belongsTo", in "hasMany"? Any error occurs. How cake uses the relationships specified in the model?

+1  A: 

By associating models together you tell CakePHP what to get from the database when you use the find() function. Example:

posts BelongsTo users = when you retrieve a post, you will also get data about user to whom this post belongs to (posts.user_id = users.id).

PawelMysior
A: 

ok if i specified like this

posts hasMany users

i cant fetch the user name rite?

udhaya
I think you're rather talking about users hasMany posts. Well in that scenario when you select a specific user, you will also get all his comments.Read about model associations in the Cookbook http://book.cakephp.org/view/78/Associations-Linking-Models-Together
PawelMysior
this should not have been an answer but a comment. As Paweł said it would be a good idea to read about the relationships at the cakebook, as this is one of the main features of Cake. Also the containable behaviour (http://book.cakephp.org/view/474/Containable) might be interesting for youAlso: If you find an answer useful you might want to reward the person by using the SO-tools
harpax
A: 

In addition to Paweł's answer:

"belongsTo", "hasMany" etc are simply terms chosen to reflect how the database is designed and how tables are related to each other, which determines how the data will be retrieved.

  • belongsTo signifies a one-to-many relationship, with the "belonging" model being on the "many" side
  • hasMany signifies the other side of a one-to-many relationship
  • hasOne signifies a one-to-one relationship
  • hasAndBelongsToMany signifies a many-to-many relationship

The specific relationship determines which table holds which foreign key and how to JOIN the tables to retrieve data automatically. Look into Normalization if you have no experience with this.

deceze