Cakephp 无法使用 set 更新表


cakephp can't update table with set

我在 cakephp 中更新数据库表时遇到问题...所以我有一个个人资料页面,登录用户可以在其中查看和更新他的个人信息。这是我的解决方案(是的,我知道这不是最好的......

if($this->request->is('post')) {
    $data = $this->request->data['user-profile'];
    // $uid = $this->Session->read("WebUser.id");
    $uid = 1;
    $user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));             
    $updated_fields = '';
    foreach($data as $key => $value) {
        if($key != 'state'){
            if(empty($value)) {                                                             
                $this->Session->setFlash("Please fill in all the required fields");
                return;
            }
        }               
        if($user_data['WebUser'][$key] != $value) {
            if($key == 'email') {
                $mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
                if($mail_check) {
                    $this->Session->setFlash("This e-mail is already registered");
                    return;
                }
            }
            $updated_fields .= "'".$key."'=>'".$value."',";
        }               
    }
    if($updated_fields != '') {
        $updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
        $this->WebUser->read(null, $uid);
        $this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
        if($this->WebUser->save()) {
            $this->printr($this->data);
            $this->WebUser->save();
            $this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
        } else {
            $this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
        }
    }
    return;
 }

因此,此代码从数据库中获取用户信息,并查找在配置文件页面上编辑的那些字段。问题是当我想保存数据时,它给我的返回是错误的并且没有保存它......有人对此有解决方案吗?

尝试放置$this->WebUser->validationErrors;在 else 部分中,检查是否存在任何验证错误。

喜欢这个:

if($this->WebUser->save()) {
                $this->printr($this->data);
                $this->WebUser->save();
                $this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
            } else {
                echo "<pre>";print_r($this->WebUser->validationErrors);die();
                $this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
            }

您是否尝试直接设置id

$this->WebUser->id = $uid;

此外,CakePHP 会在任何交易后自动更新表中modified字段。因此,您不必直接设置它(但如果需要任何其他日期值,则可以设置它)。

关于验证。我建议您阅读有关 CakePHP 中的数据验证,因为这种验证不好,它可以由模型处理。

也。您可以使用 Model::$validationErrors 从模型中获取任何验证错误。

debug($this->Recipe->validationErrors);

这段代码的问题是不想保存发布的数据(debug($this->WebUser->save) 给了我假)。最后我没有找到为什么这段代码不起作用的解决方案,但结论是你永远不需要使用更多的用户表。所以现在我有一个用户和组表,不同类型的用户连接到他们的组(管理员、用户......