Skip to content

Instantly share code, notes, and snippets.

@renan
Created April 16, 2012 12:42
Show Gist options
  • Save renan/2398540 to your computer and use it in GitHub Desktop.
Save renan/2398540 to your computer and use it in GitHub Desktop.
CakePHP HABTM save
<?php
class Post extends AppModel {
public $hasMany = array('PostsTag');
public $hasAndBelongsToMany = array('Tag');
}
<?php
class PostsController extends AppController {
public function save() {
$data = array(
'Post' => array(
'title' => 'New Post'
),
'PostsTag' => array(
array(
'order' => 1,
'Tag' => array('title' => 'Tag A')
),
array(
'order' => 2,
'Tag' => array('title' => 'Tag B')
)
)
);
$this->Post->saveAll($data, array('deep' => true));
$results = $this->Post->find('all');
debug($results); die;
}
}
<?php
class PostsTag extends AppModel {
public $belongsTo = array('Post', 'Tag');
}
# Dump of table posts
# ------------------------------------------------------------
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) DEFAULT NULL,
`body` text,
`views` int(11) NOT NULL DEFAULT '0',
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Dump of table posts_tags
# ------------------------------------------------------------
CREATE TABLE `posts_tags` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
`order` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Dump of table tags
# ------------------------------------------------------------
CREATE TABLE `tags` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL DEFAULT '',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<?php
class Tag extends AppModel {
public $hasMany = array('Post');
public $hasAndBelongsToMany = array('Post');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment