我是yiibie,我使用此链接使用了Yii 1.1: How to upload image(photo), and path entry in database with update functionality,我从这个链接http://www.yiiframework.com/wiki/349/how-to-upload-image-photo-and-path-entry-in-database-with-update-functionality/
开始关注所有内容。现在的问题是,当我为Ngo profile
上传图像时,在更改一个Ngo个人资料的图像时,其他Ngo的个人资料图像也会发生变化。例如,我有Ngo A
图片ngo1.jpg
和Ngo B
图片ngo2.jpg
。当我使用Ngo A
更新ngo3.jpg
的个人资料时,它会被更改,但也会将Ngo B
的图像更改为ngo3.jpg
。并且也没有任何Ngo被删除。当我删除它时会出现错误,表示
Error 500: <h1>CDbException</h1>
<p>CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`response_system`.`user_rate_review_ngo`, CONSTRAINT `fk_user_rate_review_ngo_ngo1` FOREIGN KEY (`ngo_id`) REFERENCES `ngo` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION). The SQL statement executed was: DELETE FROM `ngo` WHERE `ngo`.`id`=5 (C:\wamp\apps\yii\db\CDbCommand.php:357)</p><pre>#0 C:\wamp\apps\yii\db\ar\CActiveRecord.php(1745): CDbCommand->execute(). Please help me with this.
这是我的Ngo模型
<?php
/**
* This is the model class for table "ngo".
*
* The followings are the available columns in table 'ngo':
* @property integer $id
* @property string $ngo_name
* @property string $email
* @property string $address
* @property string $image
* @property string $requirement
*
* The followings are the available model relations:
* @property ClaimedNgo[] $claimedNgos
* @property UserRateReviewNgo[] $userRateReviewNgos
*/
class Ngo extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Ngo the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'ngo';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('ngo_name, email, address, image, requirement', 'required'),
array('ngo_name, email, image', 'length', 'max'=>45),
array('address', 'length', 'max'=>100),
array('requirement', 'length', 'max'=>500),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, ngo_name, email, address, image, requirement', 'safe', 'on'=>'search'),
array('image', 'length', 'max'=>255, 'on'=>'insert,update'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'claimedNgos' => array(self::HAS_MANY, 'ClaimedNgo', 'ngo_id'),
'userRateReviewNgos' => array(self::HAS_MANY, 'UserRateReviewNgo', 'ngo_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'ngo_name' => 'Ngo Name',
'email' => 'Email',
'address' => 'Address',
'image' => 'Image',
'requirement' => 'Requirement',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('ngo_name',$this->ngo_name,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('image',$this->image,true);
$criteria->compare('requirement',$this->requirement,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
这是我的Ngo Controller
<?php
class NgoController extends RController
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/admin';
public $pageOwner;
/**
* @return array action filters
*/
public function filters()
{
return array(
// 'accessControl', // perform access control for CRUD operations
// 'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function actionNgopage($id)
{
$this->layout='main';
$model2=new UserRateReviewNgo();
$this->render('ngopage',array(
'model'=>$this->loadModel($id),
'reviewmodel'=>$model2// This is for rate and reviewing
));
}
public function actionAllngo()
{
$allmodels= Ngo::model()->findAll(array('order'=>'id DESC'));
$this->layout='main';
$this->render('allngo',array('allmodels'=>$allmodels));
}
public function actionEditcomment()
{
// $this->layout='main'; //render main layout
// $model2=new UserRateReviewNgo(); //new objecct of table ratereviewngo
// $this->render('editcomment',array(
// 'model'=>$this->loadModel($id), //model+reviewmodel as a object
// 'reviewmodel'=>$model2// This is for rate and reviewing
// ));
//Yahan se hum ne kaam shuru kia he comment wala
$this->layout='main';
$rbmodel= UserRateReviewNgo::model()->findAll();
$u_id = Yii::app()->user->id;
$biz_id=$_GET['ngo_id'];
$rev_id=$_GET['rbid'];
//select rating,review from review_business where user_id=1 and id=6
$results = Yii::app()->db->createCommand()
->select('r.rate,r.review,r.id,r.user_id')
->from('user_rate_review_ngo r')
->where('r.user_id='.$u_id) //checking/comparing the current user
->andWhere('r.id='.$rev_id)//matching the review here
->queryAll();
$this->render('editcomment',array(
"u_id"=>$u_id,"biz_id"=>$biz_id,"results"=>$results,"rev_id"=>$rev_id,"rbmodel"=>$rbmodel,
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Ngo;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Ngo']))
{
$rnd = rand(0,9999); // generate random number between 0-9999
$model->attributes=$_POST['Ngo'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if($model->save())
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../img/'.$fileName); // image will uplode to rootDirectory/event/
$this->redirect(array('admin'));
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$this->layout='owner';
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$claimed=1;
//The Query is select the userid,and claimed field from claim business, where
//userid= currently logged in user and the field of claimed is equal to means, it has been claimed, and the right hass
//been given to owner. so only that owner can now view the update page.
$current_user=YII::app()->user->id;
$results = Yii::app()->db->createCommand()
->select('b.user_id,b.ngo_id,b.claimed')
->from('claimed_ngo b')
->where('b.user_id='.$current_user) //getting the current logged in user,and the claimed business bit
->andWhere('b.claimed='.$claimed)
->queryALL();
if(isset($_POST['Ngo']))
{
//$model->attributes=$_POST['Business'];
$_POST['Ngo']['image'] = $model->image;
$model->attributes=$_POST['Ngo'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../img/'.$model->image);
}
$this->redirect(array('/ngo/ngopage?id='.$model->id));
}
}
//var_dump($results);
if($results=='') //empty means, if admin is coming or someone else
{ //layout-controller-model render view
$this->pageOwner=$results[0]['ngo_id']; //by var_dump i know the position of busines_id
$this->render('update',array('model'=>$model, 'results'=>$results)); //sending results
}
else // if admin or owner comes,
// even if else not works, i still have made arrangement in update
{
$this->pageOwner=$id;
$this->render('update',array('model'=>$model, 'results'=>$results));
}
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Ngo');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Ngo('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Ngo']))
$model->attributes=$_GET['Ngo'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Ngo the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Ngo::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Ngo $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='ngo-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
这是我的view file
<?php
/* @var $this NgoController */
/* @var $model Ngo */
/* @var $form BSActiveForm */
?>
<?php $form=$this->beginWidget('bootstrap.widgets.BsActiveForm', array(
'id'=>'ngo-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->textFieldControlGroup($model,'ngo_name',array('maxlength'=>45)); ?>
<?php echo $form->textFieldControlGroup($model,'email',array('maxlength'=>45)); ?>
<?php echo $form->textFieldControlGroup($model,'address',array('maxlength'=>100)); ?>
<?php //echo $form->textFieldControlGroup($model,'image',array('maxlength'=>45)); ?>
<div class="row">
<?php echo $form->labelEx($model,'image'); ?>
<?php echo CHtml::activeFileField($model, 'image'); ?> <!--by this we can upload image-->
<?php echo $form->error($model,'image'); ?>
</div>
<?php if($model->isNewRecord!='1') ?>
<div class="row">
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/'.$model->image,"",array("width"=>200)); ?> <!--Image shown here if page is update page-->
</div>
<br>
<?php echo $form->textFieldControlGroup($model,'requirement',array('maxlength'=>200)); ?>
<?php echo BsHtml::submitButton('Submit', array('color' => BsHtml::BUTTON_COLOR_PRIMARY)); ?>
<?php $this->endWidget(); ?>
请帮帮我,谢谢。
答案 0 :(得分:-1)
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/'.$model->image,"image",array("width"=>200)); ?> <!--Image shown here if page is update page-->
试试这个