Cameron
Cameron

Reputation: 28803

Having more than one HABTM relationship to the same model

In my Cake app I several relationships on the user model to itself for various things such as likes, endorsements, friendships etc.

However Cake doesn't seem to like the way I have done this because I have repeated 'User' more than once in the array. How do I do it then?

public $hasAndBelongsToMany = array(
        'User'=>array(
            'className'              => 'User',
            'joinTable'              => 'friends',
            'with'                   => 'Friend',
            'foreignKey'             => 'user_id',
            'associationForeignKey'  => 'friend_id'
        ),
        'User'=>array(
            'className'              => 'User',
            'joinTable'              => 'endorsements',
            'with'                   => 'Endorsement',
            'foreignKey'             => 'user_id',
            'associationForeignKey'  => 'endorsed_id'
        ),
        'Interest' => array('with' => 'InterestUser')
    );

Upvotes: 0

Views: 35

Answers (1)

ADmad
ADmad

Reputation: 8100

Well you can't repeat array keys in php, nothing CakePHP can do about it. Use a different alias for the second association. In short for your second association use a different key like "User2" for eg. You can get more info about model aliases on the manual.

Upvotes: 3

Related Questions