Im trying to create a User Connections relationship:
- Following (people im following).
- Followers (people who follows me).
My question:
It is a self-relationship? How do开发者_如何学JAVA I define this?
Thanks in advance.
Untested, but somethinglike this should work:
class User extends AppModel {
var $hasAndBelongsToMany = array(
'Friend' => array(
'className' => 'User',
'joinTable' => 'friends',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
),
'Follower' => array(
'className' => 'User',
'joinTable' => 'followers',
'foreignKey' => 'user_id',
'associationForeignKey' => 'follower_id',
)
);
}
Where you've got your standard users table, plus a friends table with user_id and friend_id fields, and a followers table with user_id and follower_id fields.
What you are looking for is a HABTM relationship. Although you will be referring twice to the same model (User) instead to two separate ones form the join-table.
-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(45) NULL ,
`password` VARCHAR(100) NULL ,
`email` VARCHAR(100) NULL ,
`created` DATETIME NULL ,
`modified` DATETIME NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `followers_users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `followers_users` (
`user_id` INT NOT NULL ,
`follower_id` INT NOT NULL ,
PRIMARY KEY (`user_id`, `follower_id`) ,
INDEX `fk_followers_users_users1` (`follower_id` ASC) ,
CONSTRAINT `fk_followers_users_users`
FOREIGN KEY (`user_id` )
REFERENCES `users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_followers_users_users1`
FOREIGN KEY (`follower_id` )
REFERENCES `users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
You can create a FollowersController that extends UsersController and then further define the relationship in the follower model. So you would actually have a model to refer back to.
I hope this helps.
精彩评论