Defining One to One Relationship
To define a situation of one to one relationship in modals we think of a situation where we store information about authors and books. This means that book has only one author this is one to one relationship. To define one to one relationship you have to make two database one for books and other for author.
The query for creating the the author table is :
CREATE TABLE `authors` (
`id` int( 20 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` varchar(255 ) NOT NULL ,
`email` varchar( 255 ) NOT NULL ,
`website` varchar( 255 ) NOT NULL
);
The query for creating the the book table is :
CREATE TABLE `books` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`isbn` varchar( 255 ) NOT NULL ,
`title` varchar(255 ) NOT NULL ,
`description` text NOT NULL ,
`author_id` int( 11 ) NOT NULL
)
Creating the modal for author (author.php)
<?php
class Author extends AppModel
{
var $name = 'Author';
var $hasMany = 'Book';
}
?>
Creating the modal for book (book.php)
<?php
class Book extends AppModel {
{ var $name = 'Book';
var $hasOne = 'Author';
}
?>
Creating a Controller for book (BooksController.php)
<?php
class BooksController extends AppController
{
/*var $name = Books;
var $helpers = array(Form );*/
var $uses = array('Author', 'Book');
function index() {
$this->layout = null;
//$this->Book->recursive = 1;
$books = $this->Author->find('all');
echo "<pre>";print_r($books);die('aaa');
//$this->set(books, $books);
}
function add() {
$this->layout= null;
$books = $this->Author->find('all');
$name = '';
foreach($books as $value) {
$name[$value['Author']['id']] = $value['Author']['name'];
}
$this->set('Author',$name);
if (!empty($this->data['Book']['isbn'])) {
//echo "<pre>";print_r($this->data);die;
$this->Book->create();
$this->Book->save($this->data['Book']);
$this->redirect(array('action'=>'index'));
}
}
}
?>
Then creating the add.ctp (View/Books/add.ctp)
<?php
// echo "<pre>";
// print_r($Author);
echo $this->Form->create('Book');
?>
<fieldset>
<legend>Add New Book</legend>
<?php
echo $this->Form->input("isbn");
echo $this->Form->input('title');
echo $this->Form->input('description');
echo $this->Form->input('Author', array(
'options' => $Author,
'empty' => '-- Select Author --',
"placeholder" => "-- Select Author --",
'div'=>false,
'label'=>false,
'id'=>'author',
"name" => "data[Book][author_id]"
));
?>
</fieldset>
<?php echo $this->Form->end('Submit');?>
This is how we define one to one relationship between modals.
0 Comment(s)