简体   繁体   English

如何在Yii2中进行多对多基本CRUD操作?

[英]How to Basic CRUD operation in many-to-many relation in Yii2?

Hello to everyone out there I am new to Yii2. 大家好,我是Yii2的新手。 I just started learning Yii2 and got stuck in a condition where i have to use CRUD operation in case where I am having many-to-many relation in the backend. 我刚刚开始学习Yii2,并陷入了一种情况,即如果我的后端具有多对多关系,则必须使用CRUD操作。 I was trying to solve it but not able to understand how I can d this. 我正在尝试解决它,但无法理解如何解决。 Below I am writting the strcuture of my tables and the code. 下面我写表和代码的结构。

Table
1. test_role 1. test_role
id->first column id->第一列
role_name->second column role_name->第二列

2. test_user 2. test_user
id->primary column id-> primary列
user_name 用户名

3.user_role 3.user_role
id->primary key id->主键
user_id ->foreign key(primary key of test_user) user_id->外键(test_user的主键)
role_id ->foreign key(primary key of test_role) role_id->外键(test_role的主键)

And there is many-to-many relation between roles and users means to say that a user can have multiple roles and a role can be assigned to multiple users. 角色和用户之间存在多对多关系,这意味着一个用户可以有多个角色,并且一个角色可以分配给多个用户。 Based on this i have created the following models. 基于此,我创建了以下模型。

Model 1 TestRolephp 模型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']);
}

}

Model 2 TestUser.php 模型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']);
}
}

Below are the controllers Controller 1 TestUserController.php 以下是控制器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.');
    }
}
}

Second Controller TestRoleController.php 第二个控制器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.');
    }
}
}

Now what I want that i want to insert data into both tables. 现在,我想要将数据插入两个表中。 I want that at the time creating new user all the list of roles should display having checkbox infront of each role and vice-versa. 我希望在创建新用户时,所有角色列表应显示在每个角色的前面,并且反之亦然。 Any help can help me a lot. 任何帮助都可以帮助我很多。

My view file is ->create.php 我的查看文件是-> 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>

And create action of TestUserController.php 并创建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'));
}

Add in TestRole model 添加TestRole模型

public function getTestUsers(){
    return $this->hasMany(TestUser::className(), ['id' => 'user_id'])
        ->viaTable(TestUserRole::tableName(), ['role_id' => 'id']);
}

Add in TestUser model 添加TestUser模型

public function getTestRoles(){
    return $this->hasMany(TestRole::className(), ['id' => 'role_id'])
        ->viaTable(TestUserRole::tableName(), ['user_id' => 'id']);
}

In controller, when save models 在控制器中,当保存模型时

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM