若要删除数据库中的记录, 请按照下列步骤操作。我们已将Yii2文件夹命名为delete。
步骤1创建模型文件
在frontend / models文件夹中创建一个模型文件child.php。
<?php
namespace app\models;
use Yii;
class Child extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'child';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'meaning', 'gender'], 'required'], [['name', 'meaning'], 'string', 'max' => 100], [['gender'], 'string', 'max' => 15]
];
}
}
步骤2在控制器中创建动作
在ChildController.php文件中创建一个actionDelete动作。
<?php
namespace frontend\controllers;
use Yii;
use app\models\Child;
use yii\web\Controller;
/**
* manual CRUD
**/
class ChildController extends Controller
{
/**
* Create
*/
public function actionCreate()
{
$model = new Child();
// new record
if($model->load(Yii::$app->request->post()) && $model->save()){
return $this->redirect(['index']);
}
return $this->render('create', ['model' => $model]);
}
/**
* Read
*/
public function actionIndex()
{
$child = Child::find()->all();
return $this->render('index', ['model' => $child]);
}
/**
* Edit
* @param integer $id
*/
public function actionEdit($id)
{
$model = Child::find()->where(['id' => $id])->one();
// $id not found in database
if($model === null)
throw new NotFoundHttpException('The requested page does not exist.');
// update record
if($model->load(Yii::$app->request->post()) && $model->save()){
return $this->redirect(['index']);
}
return $this->render('edit', ['model' => $model]);
}
/**
* Delete
* @param integer $id
*/
public function actionDelete($id)
{
$model = Child::findOne($id);
// $id not found in database
if($model === null)
throw new NotFoundHttpException('The requested page does not exist.');
// delete record
$model->delete();
return $this->redirect(['index']);
}
}
步骤3运行
在浏览器上运行它。
http://localhost/delete/frontend/web/index.php?r = child%2Findex
查看上面的快照, 单击表最后一行中的”删除”选项。
查看上面的快照, 相应的行将从表中删除。
下载此示例