Yii:如何从另一个控制器动作中调用控制器动作?

Yii:如何从另一个控制器动作中调用控制器动作?

问题描述:

When I delete a 'type' i set isActive = 0;

Every 'type' 'has many' 'causal'

So when disabling a type i want disable every causal

in type controller i'm trying this

$model = $this->loadModel($id);
$model->isActive = 0;

foreach ($model->causalsObj as $key => $causal ) {
   $causal = CausalController::delete($causal->id);
}

$model->save();

This doesn't work (PHP error during ajax call)

当我删除'type'时,我设置isActive = 0; p>

每个“类型”都有很多“因果关系” p>

因此,当禁用某种类型时,我希望禁用类型中的每一个因果 p>

strong>控制器我正在尝试这个 p>

  $ model = $ this-> loadModel($ id); 
 $ model-> isActive = 0; 
 \  nforeach($ model-> causalsObj as $ key => $ causal){
 $ causal = CausalController :: delete($ causal-> id); 
} 
 
 $ model-> save(  ); 
  code>  pre> 
 
 

这不起作用(在ajax调用期间出现PHP错误) p> div>

That should go into the model, not the controller, I'd use afterSave. so in the CasualType:

public function afterSave(){
   if(!$this->isActive){
       Casual::model()->deleteAll('type_id = '.$this->id);
   }

   return parent::afterSave();
}

If you don't actually mean 'delete' but deactivate you can still do this in one single query using CActiveRecord::updateAll:

public function afterSave(){
   if(!$this->isActive){
       Casual::model()->updateAll(array('isActive' => 0), 'type_id = '.$this->id);
   }

   return parent::afterSave();
}

Instantiating a controller in another controller does not make sense, controllers are there to handle user requests, not to hold your business logic

Looks like the problem is in your foreach loop, if you already have a relation set up you should be able to access it with $model->causal. If that doesn't work, check your relations are working correctly

$model = $this->loadModel($id);
$model->isActive = 0;
foreach ($model->causal as $item){
   $item->delete();
}
$model->save();

Do you have the following at the top of your code?

Yii::import('application.models.CausalController');

This should make it possible.

Also using SuVeRa's way to delete the items would be nicer:

foreach ($model->causalsObj as $key => $causal ) {

   $causal->delete(); 

}

Or you can create a function in CausalController which deletes all causal's for a given id.