簡體   English   中英

Yii使用用戶身份對象分配外鍵值

[英]Yii assigning foreign key value using user Identity object

在我的Web應用程序中,我有3個表,用戶類型分別為producer_offer,consumer_req,admin和一個user table, producer,consumer 關系

user.id=producer_offer.offered_by
user.id=consumer_req.requested_by

基本上基於使用用戶ID登錄的用戶,它應該根據用戶類型和ID自動分配給Consumer_req和producer_offer表中的外鍵。我嘗試了以下代碼,但在userController中不起作用

public function actionCreate()
    {
        $model=new User;
        // $this->performAjaxValidation($model);
        if (isset($_POST['User'])) {
            $model->attributes=$_POST['User'];
            if ($model->save()) {

                if($model->user_type=='producer'){
                    $producer=new ProducerOffer;
                    $producer->offered_by=$model->id;
                    //$producer->save();
                }
                if($model->user_type=='consumer'){

                    $consumer=new ConsumerReq;
                    $consumer->requested_by=$model->id;
                    //$consumer->save();
                }

                $this->redirect(array('view','id'=>$model->id));
            }
        }

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

我的userIdentity類代碼

class UserIdentity extends CUserIdentity

{

private $_id;


public function authenticate()
{
    $user = User::model()->findByAttributes(array(
            'email'=>$this->username));
    if ($user === null) {

        $this->errorCode=self::ERROR_USERNAME_INVALID;
    } else if ($user->pass !==
    hash_hmac('sha256', $this->password,
            Yii::app()->params['encryptionKey']) ) {

        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    } else {
        $this->errorCode=self::ERROR_NONE;
        $this->setState('type', $user->user_type);
        $this->setState('id', $user->id);
        $this->_id = $user->id;

    }
    return !$this->errorCode;

}

public function getId() {
    return $this->_id;

}

}

在我的siteController中,我在actionSetup()有此代碼用於分配用戶類型

public function actionSetup(){
        $auth->assign($user->type,$user->id);
    }

但是執行時出現以下錯誤,這

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`AFFM`.`producer_offer`, CONSTRAINT `producer_offer_ibfk_2` FOREIGN KEY (`offered_by`) REFERENCES `user` (`id`)). The SQL statement executed was: INSERT INTO `producer_offer` (`offered_vegetable`, `offered_qty`, `unit_cost`, `unit_delivery_cost`, `offered_date`, `booking_status`, `booked_by`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6)

您將在product_offer表中插入一條記錄,但是沒有插入外鍵字段offered_by 如果要允許它為空,則必須在數據庫中將此字段設置為NULL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM