Model many-to-one relations function - Agile Yii book ^^


(Mythicalprogrammer) #1

So, in this book chapter 6. We have 3 tables now.

What’s confusing is the relation function.

Project Model’s relations function is defined as:


public function relations()

{

    return array(

    'issues' => array(self::HAS_MANY, 'Issue', 'project_id'),

    'users' => array(self::MANY_MANY, 'User', 'tbl_project_user_assignment(project_id, user_id)'),

    );

}

The Issue table relationship to Project table is one to many. But! The author and the code generator left it as:

Issue Model:


public function relations()

{

    // NOTE: you may need to adjust the relation name and the related

    // class name for the relations automatically generated below.

    return array(

        'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),

        'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),

        'project' => array(self::BELONGS_TO, 'Project', 'project_id'),

    );

}

The only relations we have are 3 foreign keys. When I looked up Yii’s Documentation there’s a HAS_ONE AR option.

So therefore my question is:

Should it need to defined it? If not why? Redundant for some reason?

If I do need to state this relationship is this it (am I doing it right):


    'project_id' => array(self::HAS_ONE, 'Project', 'project_id'),


(Ft07) #2

A HAS_MANY/HAS_ONE relationship corresponds to a BELONGS_TO relationship in the model that represents the other table. You don’t have to declare relations in both models, just in the model you use as primary in your query.

Read more about Relational AR in the guide.

/Tommy


(Mythicalprogrammer) #3

Thank you!