Akelos Framework v1 forum archive. This forum is no longer maintained. To report bugs please visit https://github.com/akelos/akelos/issues
    • CommentAuthorhaakon
     
    Hi,

    I want to make a many-to-many relationship between the User table and the User table ;)

    And I also would like the model to be called Friends.

    So I can go to $User->Friends to get all the friends.

    Or should I just make a "Friends" model, without any relations, and manually fill $User->Friends with a user-defined function, whenever I need it?

    Any thoughts, sollutions?
    • CommentAuthorsuthern
     
    many to many relationships can be quite tricky.

    I usually try to reduce it to a couple one to many relationships.
    Perhaps something like this would work?

    Tablename: users
    Fields: Id, name

    Tablename: friends
    Fields: user_id, friend_id

    This would mean that for each 'friendship' you would have two entries in the 'Friends' table. One for each direction.

    You would also need to put something like THIS in your 'friend' model:
    var $belongs_to = array('user', 'friend' => array('class_name' => 'user', 'primary_key_name' => 'friend_id' ));

    and you would need to put something like THIS also in your 'friend' model:
    function afterSave() {
    // ----!! PSUDO CODE !! -----
    // swap ids -- create may not be correct function to use here!
    $new_friendship = $this->create(array('friend_id' => $this->user_id, 'user_id' => $this->'friend_id'));

    // check to see if the 'mirrored' version already exists
    $alt_friendship = $this->find('all',arrray('conditions' => array ('user_id = ? AND friend_id = ?',$new_friendship->user_id,$new_friendship->friend_id)))

    // if it does, abort the function
    if(!empty($alt_friendship)) return true;

    // mirrored version does not exist, so we go ahead and save the new mirrored version
    $new_friendship->save();
    }


    Using this method you could call $User->friends->load(), and presto, all the person's friends are loaded.
    • CommentAuthorsuthern
     

    Or perhaps the big 'afterSave()' function could be better written as

    function afterSave() {
    // ----!! PSUDO CODE !! -----
    // check to see if the 'mirrored' version already exists
    $alt_friendship = $this->find('all',arrray('conditions' => array ('user_id = ? AND friend_id = ?',$this->friend_id,$this->user_id)))
    
    // if it does, abort the function
    if(!empty($alt_friendship)) return true;
    
    // else we create (which means create and save)
    $this->create(array('friend_id' => $this->user_id, 'user_id' => $this->'friend_id'));
    
    }