-2

Hy i am trying to create a follow feature to my website so user can follow each other , I am using Cakephp what kind of relation should i use , what should i name the tables.

NB: I created a user table + follow table containing user_id and follower_id !

sleimanx2
  • 2,036
  • 1
  • 13
  • 9

2 Answers2

2

If you don't need to save any information about the relation, then hasAndBelongsToMany is the natural relation to use in this case. Try this:

// User Model
var $hasAndBelonsToMany = array(
    'Follower' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'follower_id'
        'joinTable' => 'followers_users'
    )
)

then you must create the users table as normal, and a table 'followers_users' with columns: 'id', 'user_id', 'follower_id' (and 'created' and 'updated' if you need them).

EDIT : To retrieve your data (read here) you do it as usual:

$this->User->find('all', array('conditions' => array('id' => 1)));

Then you'll get an array like:

Array(
    [User] => array(
        [id] => 1
        [name] => xxxx
    )
    [Follower] => array(
        [0] => array(
            [id] => 2
            [name] => yyyy
        )
        [1] => array(
            [id] => 3
            [name] => zzzz
        )
    )
)

To save your data (read here and here), you need to create an array like:

array(
    [User] => array(
        [id] => 1
        [name] => xxx
    )
    [Follower] => array(
        [0] => array(
            [id] => 2
        )
        [1] => array(
            [id] => 3
        )
    )
)
Community
  • 1
  • 1
Choma
  • 708
  • 12
  • 24
0

Explanation of what you are looking / example is right in the book:

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#multiple-relations-to-the-same-model

Similar example per the book:

"It is also possible to create self associations as shown below:"

<?php
class Post extends AppModel {
    public $name = 'Post';

    public $belongsTo = array(
        'Parent' => array(
            'className' => 'Post',
            'foreignKey' => 'parent_id'
        )
    );

    public $hasMany = array(
        'Children' => array(
            'className' => 'Post',
            'foreignKey' => 'parent_id'
        )
    );
}
Dave
  • 28,833
  • 23
  • 113
  • 183