HABTM association is used when you have two models that need to be joined up, repeatedly, many times in many different ways.
So below is the following steps to follow to use the above relationship. First we create the database and its tables
The Tables
Now, we create our database tables.We need to have a join table linking both models. So, for our example, we will need a User table, Book table and a join table for linking Book to User. So here are the 3 database tables that we will need to create:
CREATE TABLE user (
id int(11) NOT NULL auto_increment,
name varchar(255) NOT NULL,
description text NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE book (
id int(11) NOT NULL auto_increment,
name varchar(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE book_user (
book_id int(11) NOT NULL,
user_id int(11) NOT NULL,
PRIMARY KEY (book_id,user_id)
);
The Models
Next, lets create our models. We will need to have a User model and a Book model. We need to setup the HABTM relationship on both models so that any user can have any book and vice versa.
Lets create the Book Model:
<?php
class Book extends AppModel {
var $name = 'Book';
var $hasAndBelongsToMany = array(
'User' =--> array(
'className' => 'User',
'joinTable' => 'book_user',
'foreignKey' => 'book_id',
'associationForeignKey' => 'user_id'
),
);
}
?>
Then we create our User model. In the case of the user, I require the name of the user to be unique just like the book, but I want to also make sure that users provide a description for the user. Below is the source code:
<?php
class User extends AppModel {
var $name = 'User';
var $hasAndBelongsToMany = array(
'Book' =--> array(
'className' => 'book',
'joinTable' => 'book_user',
'foreignKey' => 'recipe_id',
'associationForeignKey' => 'book_id'
),
);
}
?>
The Controllers
Now lets we create the controllers by using some functions like add/edit/delete. Below is the controller for the Book Controller
<?php
class BookController extends AppController {
public $uses = array('Book', 'User');
function index() {
}
function add() {
}
function edit() {
}
function delete() {
}
}
?>
And below is the code for the User controller:
<?php
class UserController extends AppController {
public $uses = array('User', 'Book');
function index() {
}
function add() {
}
function edit() {
}
function delete() {
}
}
?>
The Views
Now we create the views:
In case of both Book and User,there is a view for all the basic actions that I can perform.
<!-- app/View/User/file/user.ctp -->
0 Comment(s)