php - 如何在不使用 Controller 的情况下更新外键? - yii, php

标签 php mysql yii

我最近创建了一个数据库,其中包含用户表、移动帐户表和支付列表表。 paylists 和 mobile_accounts 都链接回用户,并且都具有外部 ID“user_id”。当我让用户创建他们自己的付费列表或 mobile_accounts 时,我使用了我在用户模型中创建的一个名为“addUserId”的函数。我在传递当前模型和 user_id 的每个特定 Controller (即 paylists 或 mobile_accounts)中调用该函数。这对我来说很好,但它似乎有点像一个变通系统。 关于如何使用外键更新数据库,我是否遗漏了一些非常简单的东西?还是我以后只需要继续创建这样的功能?

这是Paylist Controller 中的代码

public function actionCreate()
{
    $model=new Paylist;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Paylist']))
    {
        $model->attributes=$_POST['Paylist'];
        if($model->save())
            // adds the current UserId to the table
            User::model()->addUserId($model);
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

这是用户模型中的代码

// adds the user id to your data table, takes in the user id and adds it to specified model 
public function addUserId($model)
{  
    $accountid = $model->id;
    $current_email = Yii::app()->user->getId();
    // gets the current id of the user 
    $user = User::model()->findByAttributes(array('email'=>$current_email));
    // extracts out the id of the current user 
    $user_id = $user->id; 
    $model->updateByPk($accountid,array('user_id'=>$user_id)); 

}

最佳答案

您可以在模型中使用 CActiveRecord::beforeSave() 方法:

public function beforeSave(){
   if($this->isNewRecord){
       User::model()->addUserId($this);
   }
   return parent::beforeSave();
}

并更改 addUserId 方法:

public function addUserId($model)
{  
    $accountid = $model->id;
    $current_email = Yii::app()->user->getId();
    $user = User::model()->findByAttributes(array('email'=>$current_email));
    $model->user_id = $user->id; ; // just set user_id attribute
}

您还可以在 User 模型中实现方法 getCurrentUserId 返回当前用户 ID 并在 beforeSave 中调用此方法:

public function beforeSave(){
   if($this->isNewRecord){
       $this->user_id = User::getCurrentUserId();
   }
   return parent::beforeSave();
}

关于php - 如何在不使用 Controller 的情况下更新外键? - yii, php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24655825/

相关文章:

mysql - 单行列出价格并按日期分组

php - Yii 还记得我功能吗?

php - Yii dropDownList 默认值

javascript - 表单提交按钮 - 每次提交时更改操作页面

php - MAMP 所有虚拟主机都指向 htdocs 文件夹

php - 多个 PHP MySQL 更简单的查询与一个更复杂的查询,

Mysql查询显示两个表中不匹配的记录,如旧记录和新记录

php - 查找在 PHP(和/或 SMARTY)中定义变量的位置?

c++ - 用mysql原生函数进行字节序转换

php - yii mysql 通过查询生成器使用子查询