Question

So here's the scenario:

I have two table, Issue & Project.

A Project can have many Issue and an Issue can exactly one project.

Since Issue is many to one, do you have to define it?

Cause I know in Project Model I have:

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)'),
    );
}

For Issue Model I have nothing but foreign keys:

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'),
    );
}

I'm guessing anything to one relationship does not need to be define?

Thank you in advance.

BTW, I'm doing agile Yii book and I ended up asking myself this question. There's a has-one option in AR class (http://www.yiiframework.com/doc/guide/database.arr).

But is this case optional for some reason?

Was it helpful?

Solution

It helps me to think of the difference between BELONGS_TO and HAS_ONE as "where is the foreign key stored"? If the Project model stored "Issue_Id" then potentially Issue could have many Projects. You use the HAS_ONE relationship to state that even if Issue COULD have many projects, it only has ONE.

However, the more common case is if you are storing the Project_Id in the Issue model (and I assume you are). Then you have to use the BELONGS_TO relationship. It appears you have defined the relationships correctly above.

Someone posted a similar question relating to Yii relations here that I helped answer: yii - using relation HAS_ONE to get data from the related table to display in list page

As to your concern about "needing" to define relationships, you don't "need" to define any. You could write your own SQL queries to do the same thing. The ActiveRecord relations are just a convenience thing to make querying for related records simpler. If you are never going to look up an Issue's Project, then you don't "need" to define the "project" BELONGS_TO relationship.

Without actually seeing your database structure it looks to me like you have everything set up correctly. You can now easily make both $issue->project and $project->issues "lazy" relational queries, taking full advantage of the power of the Relational Active Record. Cheers and good luck with project!

OTHER TIPS

In your Issue model you already have the relation specified as BELONGS_TO the project model.

I also just got the new yii-book. It helped me alot!

Happy coding :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top