yii2 ActiveController中的Delete和DeleteAll操作覆盖


Delete and DeleteAll action override in yii2 ActiveController

大家好,我正在yii2中实现restful api,并且在ActionDeleteActionDeleteall 中发生冲突

当我在类似http://localhost/yii2-api/api/modules/v1/countries/CD的url中传递一个参数时,它工作正常,并通过DELETE请求从数据库中删除记录CD。我不知道如何在url中传递多个codes,使其重定向到actionDeleteall。这是我的controller代码。

class CountryController extends ActiveController
{
public $modelClass = 'api'modules'v1'models'Country';
public function actions()
{
    $actions = parent::actions();
    unset($actions['index']);
    unset($actions['create']);
    unset($actions['delete']);
    unset($actions['update']);
    unset($actions['view']);
    return $actions;
}
public function actionDelete($id)
{
    $model=$this->findModel($id);
    if($model->delete())
    {
        $this->setHeader(200);
        echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
    }
    else
    {
        $this->setHeader(400);
        echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
    }
}
public function actionDeleteall()
{
    $ids=json_decode($_REQUEST['codes']);
    $data=array();
    foreach($ids as $id)
    {
        $model=$this->findModel($id);
        if($model->delete())
            $data[]=array_filter($model->attributes);
        else
        {
            $this->setHeader(400);
            echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
            return;
        }
    }
    $this->setHeader(200);
    echo json_encode(array('status'=>1,'data'=>$data),JSON_PRETTY_PRINT);
}
}

这是我的urlmanager代码

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => false,
        'showScriptName' => false,
        'rules' => [
            [
                'class' => 'yii'rest'UrlRule',
                'controller' => 'v1/country',   // our country api rule,
                'tokens' => [
                    '{id}' => '<id:''w+>'
                ],
            ]
        ],
    ]

让我知道如何覆盖该操作并在传递了多个codes的情况下访问它。感谢

您可以发布一个id值数组并执行循环

这只是一个简短的建议
显然,你应该评估一个适当的错误,一个结果回声管理

  public function actionDelete($myArray)
  {
      foreach( $myArray as $key => $value){
        $model=$this->findModel($value)
        $model->delete();
      } 
}

如果你在中有你的id数组

 $myArray[0] = 'CD';
 $myArray[1] = 'AA'; 

url应该是

http://localhost/yii2-api/api/horsebuzz/api/web/v1/countries/myArray=[27,28]

或者,如果您使用代码,请使用actionDelete($code)。。。上的广告

如果使用UrlHelper ,效果会更好

  Url::to(['/countries/delete' , 'myArray' => [27,28] ]); 
  Url::to(['/countries/delete' , 'myArray' => $myArray ]); 

首先禁用urlmanager 中的严格解析

'enableStrictParsing' => false

然后您可以使用任何方法调用自定义操作url将看起来像

http://localhost/yii2-api/api/web/v1/country/uraction