porton
porton

Reputation: 5805

Yii: Naming relations and fields

I wrote some Yii code with the same name for a DB field and a relation:

public function relations()
{
    return array(
        'kin' => array(self::BELONGS_TO, 'Kin', 'kin'),
        'child' => array(self::BELONGS_TO, 'Child', 'child'),
    );
}

Now I understand that this is wrong, because relations "cover" over field attributes and queries like $this->child to get child ID do not work.

My question: Which naming scheme would you suggest for DB fields and for relations?

Upvotes: 0

Views: 117

Answers (1)

Joe Miller
Joe Miller

Reputation: 3893

Firstly, I'd avoid naming your primary key after the table. It makes this kind of statement difficult to read. I always name my primary keys something like childId or kinId; that way it's clear what field you're talking about.

I think there is no hard and fast rules about naming, except to use what makes sense in your context. For something like this, assuming I've understood your table structure correctly, I'd be inclined to go for this: Table 1: kin Primary key: kinId

Table 2: child Primary key: childId Foreign key from table kin: fkKinId

Then, assuming that one kin can have many children, your relation in the Kin model becomes:

public function relations()
{
    return array(
        'children' => array(self::HAS_MANY, 'Child', 'fkKinId'),
    );
}

You can then call the child model for your kin using $this->children if you're inside the Kin model.

Upvotes: 3

Related Questions