我最近创建了一个数据库,其中包含用户表、移动帐户表和支付列表表。 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/