[英]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.