大家好,我是 Yii2 的新手。我刚开始学习 Yii2 并陷入了必须使用 CRUD 操作的情况,以防我在后端有多对多关系。我试图解决它,但无法理解我该怎么做。下面我正在编写表格的结构和代码。
表
1. test_role
id->第一列
role_name->第二列
2. test_user
id->主列
user_name
3.user_role
id->主键
user_id ->外键(test_user的主键)
role_id ->外键(test_role的主键)
角色和用户之间存在多对多的关系,意思是说一个用户可以有多个角色,一个角色可以分配给多个用户。基于此,我创建了以下模型。
模型 1 TestRolephp
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "test_role".
*
* @property integer $id
* @property string $role_name
*
* @property TestUserRole[] $testUserRoles
*/
class TestRole extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'test_role';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['role_name'], 'required'],
[['role_name'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'role_name' => 'Role Name',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTestUserRoles()
{
return $this->hasMany(TestUserRole::className(), ['role_id' => 'id']);
}
}
模型 2 TestUser.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "test_user".
*
* @property integer $id
* @property string $username
*
* @property TestUserRole[] $testUserRoles
*/
class TestUser extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'test_user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username'], 'required'],
[['username'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTestUserRoles()
{
return $this->hasMany(TestUserRole::className(), ['user_id' => 'id']);
}
}
下面是控制器 Controller 1 TestUserController.php
<?php
namespace app\controllers;
use Yii;
use app\models\TestUser;
use app\models\TestUserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TestUserController implements the CRUD actions for TestUser model.
*/
class TestUserController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all TestUser models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new TestUserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single TestUser model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new TestUser model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new TestUser();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing TestUser model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing TestUser model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the TestUser model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return TestUser the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestUser::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
第二个控制器 TestRoleController.php
<?php
namespace app\controllers;
use Yii;
use app\models\TestRole;
use app\models\search\TestRoleSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TestRoleController implements the CRUD actions for TestRole model.
*/
class TestRoleController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all TestRole models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new TestRoleSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single TestRole model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new TestRole model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new TestRole();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing TestRole model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing TestRole model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the TestRole model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return TestRole the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestRole::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
现在我想要将数据插入到两个表中。我希望在创建新用户时所有角色列表都应显示在每个角色前面都有复选框,反之亦然。任何帮助都可以帮助我很多。
我的视图文件是 ->create.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\TestUser */
$this->title = 'Create Test User';
$this->params['breadcrumbs'][] = ['label' => 'Test Users', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="test-user-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
并创建 TestUserController.php 的动作
public function actionCreate()
{
$user = new TestUser;
$role = new TestRole;
if($user->load(Yii::$app->request->post()) && $role->load(Yii::$app->request->post()) &&
$user->validate() && $role->validate())
{
$user->save(false);
$role->save(false);
$user->link('testRoles', $role); //add row in junction table
return $this->redirect(['index']);
}
return $this->render('create', compact('user', 'role'));
}