Table Associations
CREATE TABLE `posts` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
`date` datetime default NULL,
`content` text,
`user_id` int(11) default NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `comments` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(100) default NULL,
`content` text,
`post_id` int(11) default NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(100) default NULL,
`email` varchar(150) default NULL,
`firstname` varchar(60) default NULL,
`lastname` varchar(60) default NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `tags` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(100) default NULL,
`longname` varchar(255) default NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `posts_tags` (
`id` int(11) unsigned NOT NULL auto_increment,
`post_id` int(11) unsigned default NULL,
`tag_id` int(11) unsigned default NULL,
PRIMARY KEY (`id`)
);
Models:
class Post extends AppModel{
var $name='Post';
var $belongsTo=array('User');
var $hasMany = array('Comment');
var $hasAndBelongsToMany=array('Tag');
}
class User extends AppModel{
var $name='User';
var $hasMany=array('Post');
}
class Comment extends AppModel{
var $name='Comment';
var $hasMany =array('Post');
}
class Tag extends AppModel{
var $name="Tag";
var $hasAndBelongsToMany = array('Post');
}
Many to many relationship( “has and belongs to many”)
For “has and belongs to many” tables, the name must be arranged in alphabetical order with each associated table’s name separated by an underscore. eg. posts db and tags ==> posts_tags db
Advanced Tip:
var $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id',
'conditions'=>null,
'fields'=>null
)
);
Controllers:
class PostsController extends AppController{
var $name='Posts'
var $scaffold; //Will generate scaffold
}
class UsersController extends AppController{
var $name='Users'
}
class CommentsController extends AppController{
var $name='Comments'
}
class TagsController extends AppController {
var $name = 'Tags';
var $scaffold;
}
Layouts
<?=$html->css('cake.generic');?>
Cake’s styles have been implemented without the scaffolding’s default titles and such.
Cake command:
$ cake bake controller
$ cake bake model
$ cake bake view
$ cake bake project
You can even enter the name of the resource if you want to bypass interactive mode and
just generate the file:
$ cake bake controller tags
$ cake bake model comment
Don’t forget to include the -app parameter if your Cake console installation requires you
to do so for Bake to access your working application folder:
$ cake bake controller tags -app /serverroot/blog/app/
No comments:
Post a Comment