Yii使用用户标识对象分配外键值

时间:2014-02-11 06:43:02

标签: php mysql sql yii yii-components

在我的Web应用程序中,我有3个名为producer_offer,consumer_req,admin的表用户类型和一个user table, producer,consumer。 关系

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

基于用户id登录的用户,它应该根据user_req和producer_offer表中的外键自动分配用户类型和id 我尝试了以下代码,但它不在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)

1 个答案:

答案 0 :(得分:0)

您在product_offer表格中插入了一条记录,但您并没有将外键字段offered_by置于无关紧要状态。如果要允许此为空,则必须在数据库中将此字段设置为NULL。