[英]How to Basic CRUD operation in many-to-many relation in Yii2?
大家好,我是Yii2的新手。 我剛剛開始學習Yii2,並陷入了一種情況,即如果我的后端具有多對多關系,則必須使用CRUD操作。 我正在嘗試解決它,但無法理解如何解決。 下面我寫表和代碼的結構。
表
1. test_role
id->第一列
role_name->第二列
2. test_user
id-> primary列
用戶名
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'));
}
添加TestRole模型
public function getTestUsers(){
return $this->hasMany(TestUser::className(), ['id' => 'user_id'])
->viaTable(TestUserRole::tableName(), ['role_id' => 'id']);
}
添加TestUser模型
public function getTestRoles(){
return $this->hasMany(TestRole::className(), ['id' => 'role_id'])
->viaTable(TestUserRole::tableName(), ['user_id' => 'id']);
}
在控制器中,當保存模型時
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'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.