Skip to content

M2M relation: Custom field names in relationTable #7

Description

@malja

Hi,

I would like to make a change in addRelationManyToMany method to accept source and target fields for relation table.

/**
 * Add a ManyToMany relation
 *
 * @param        $sourceField   - model source field
 * @param        $classRelation - relation model name
 * @param        $targetField   - related model field
 * @param        $relationTable - mysql table containing the two models ID
 * @param string $aliasRelation - override relation auto naming className
 * @param string $relationTableSourceField - Field in relation table 
 * corresponding with source field of this model
 * @param string $relationTableTargetField - Field in relation table 
 * corresponding with target field of class relation.
 *
 * @throws Exception
 */
protected static function addRelationManyToMany(
    $sourceField,
    $classRelation,
    $targetField,
    $relationTable,
    string $aliasRelation = ''
    string $relationTableSourceField = '', // <===== this is new
    string $relationTableTargetField = '',  // <===== this is new
)

Under the hook, it could fall back to values of $sourceField and $targetField when empty. It makes sure older code still works fine.

if ('' === $relationTableSourceField) {
    $relationTableSourceField = $sourceField;
}

if ('' === $relationTableTargetField) {
    $relationTableTargetField = $targetField;
}

I'm not sure this is not too hacky. There are too many parameters. It could be solved by passing an array instead of list of parameters.

Concrete implementation should be object to further discussion.

Background

I have a database with following tables and fields:

users
    - id

tags
    - id

user_tags
    - id_user
    - id_tag

Each user should be able to have multiple tags. For this purpose, there is a user_tags relation table.
Defining new many to many relation with:

// .. inside UserModel
self::addRelationManyToMany("id", "TagModel", "id", "user_tags");

// .. inside TagModel
self::addRelationManyToMany("id", "UserModel", "id", "user_tags");

doesn't work. Many to many relation requires source and relation table to share source and target fields. For example following database configuration would work:

users
    - id_user

tags
    - id_tag

user_tags
    - id_user
    - id_tag

I like to name my primary key id, because anything else is just unnecessary ballast.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions