Two tables:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(32) default NULL
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `privileges` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`users_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Models:
class Users Extends Model
{
//...
public function initialize()
{
$this->hasOne('id', 'Privileges', 'users_id', ['alias' => 'privilege']);
}
}
class Privileges extends Model
{
const NAME_ADMINISTRATOR = "Administrator";
const NAME_ULTRAMAN = "Ultraman";
// ...
public function initialize()
{
$this->belongsTo('users_id', 'Users', 'id');
}
}
In the UsersController:
public function editAction($id)
{
$user = Users::findFirstById($id);
if ($this->request->isPost())
{
// After $user->save(), I want to save this user's privileges.
// this will post 'Administrator' or 'Ultraman'
$privilege = $this->request->getPost("privilege");
if (! empty($privilege))
{
if (isset($user->privilege->id)) {
$user_privilege = Privileges::findFirstById($user->privilege->id);
} else {
$user_privilege = new Privileges();
$user_privilege->users_id = $user->id;
}
//New Group!!! But it seems can't be modified!
$user_privilege->name = $privilege;
// modify the user's group
if ($user_privilege->save() == false) {
foreach ($user_privilege->getMessages() as $message) {
$this->flash->error((string) $message);
}
} else {
$this->flash->success($user->name . " User's Group Modified successfully!");
}
}
}
}
The code $user_privilege->save()
CAN insert a user's new privilege, but it CANNOT modify a user's privilege! (Can't modify it's privileges.name). Why?