[sql]
CREATE TABLE IF NOT EXISTS `permissions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`displayName` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`company_id` int(11) NOT NULL,
`dashboard_type` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `company_id` (`company_id`)
)
CREATE TABLE IF NOT EXISTS `roles_permissions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_role_permissions_permissions1` (`permission_id`),
KEY `fk_table1_roles1` (`role_id`)
)
[/sql]
[php]
Role Model:
public $hasAndBelongsToMany = array(
‘Permission’ => array(
‘className’ => ‘Permission’,
‘joinTable’ => ‘roles_permissions’,
‘foreignKey’ => ‘role_id’,
‘associationForeignKey’ => ‘permission_id’,
‘unique’ => ‘keepExisting’,
‘conditions’ => ”,
‘fields’ => ”,
‘order’ => ”,
‘limit’ => ”,
‘offset’ => ”,
‘finderQuery’ => ”,
‘deleteQuery’ => ”,
‘insertQuery’ => ”
)
);
Permission model:
public $hasAndBelongsToMany = array(
‘Role’ => array(
‘className’ => ‘Role’,
‘joinTable’ => ‘roles_permissions’,
‘foreignKey’ => ‘permission_id’,
‘associationForeignKey’ => ‘role_id’,
‘unique’ => ‘keepExisting’,
‘conditions’ => ”,
‘fields’ => ”,
‘order’ => ”,
‘limit’ => ”,
‘offset’ => ”,
‘finderQuery’ => ”,
‘deleteQuery’ => ”,
‘insertQuery’ => ”
)
);
RolePermission Model:
public $belongsTo = array(
‘Role’ => array(
‘className’ => ‘Role’,
‘foreignKey’ => ‘role_id’,
‘conditions’ => ”,
‘fields’ => ”,
‘order’ => ”
),
‘Permission’ => array(
‘className’ => ‘Permission’,
‘foreignKey’ => ‘permission_id’,
‘conditions’ => ”,
‘fields’ => ”,
‘order’ => ”
)
);
in Role controller:
public function add() {
$roleData = $this->request->data;
$roleToSave = array();
$roleToSave[‘Role’][‘name’] = $roleData[‘name’];
$roleToSave[‘Role’][‘dashboard_type’] = $roleData[‘dashboard_type’];
$roleToSave[‘Role’][‘company_id’] = 1;
$permissions = $roleData[‘permissions’]; //permissions (array)
$roleToSave[‘Permission’][‘Permission’] = $permissions;
$this->Role->create();
$this->Role->saveAll($roleToSave);
}
Firstly your data should look like this:
array(
‘Role’ => array(
‘name’ => ‘3’
),
‘Permission’ => array(
‘Permission’ => array(
0 => ‘3’
)
)
and same for edit but one change
$this->id = $roleData[‘id’];
[/php]