bephp/activerecord

[Probably doc enhancement or feature request] Relations

userlond opened this issue · 2 comments

Let's say we have 2 tables

group(PK id, name)
item(PK id, FK group_id, name)

Item belongs to group using group_id foreign key, which points to group primary key.

Models' code is below, question is in comments:

class Group extends ActiveRecord
{
    public $relations = [
       // direct relation
       // I believe format is [relation_type, child_namespaced_classname, foreign_key] ?
        'items' => [self::HAS_MANY, 'Item', 'group_id'],
    ];
}

class Item extends ActiveRecord
{
    public $relations = [
        // inverse relation
        // I believe format is [relation_type, parent_namespaced_classname, primary_key_of_parent] ?
        'items' => [self::BELONGS_TO, 'Group', 'id'],
    ];
}

But in the docs the third parameter of direct relation is the same as the third parameter of inverse relation:

class User extends ActiveRecord{
    public $table = 'user';
    public $primaryKey = 'id';
    public $relations = array(
        'contacts' => array(self::HAS_MANY, 'Contact', 'user_id'),
        'contact' => array(self::HAS_ONE, 'Contact', 'user_id'),
    );
}
class Contact extends ActiveRecord{
    public $table = 'contact';
    public $primaryKey = 'id';
    public $relations = array(
        'user' => array(self::BELONGS_TO, 'User', 'user_id'),
    );
}

Please explain us the parameters of relations :)

self::HAS_MANY | self::HAS_ONE need set child_classname and foreign_key field name of child
self::BELONGS_TO need set parent_classname and field_name in current class.

so the item class should be like this:

class Item extends ActiveRecord
{
public $relations = [
// inverse relation
// I believe format is [relation_type, parent_namespaced_classname, foreign_key_in_current_table] ?
'items' => [self::BELONGS_TO, 'Group', 'group_id'],
];
}

Thanks for reply