首页 文章

如何在Yii2中以多对多关系进行基本的CRUD操作?

提问于
浏览
0

大家好,我是Yii2的新手 . 我刚刚开始学习Yii2并陷入了必须使用CRUD操作的情况,以防我在后端有多对多的关系 . 我试图解决它,但无法理解我怎么能这样做 . 下面我正在编写表格和代码的结构 .


test_role
id->第一列
role_name->第二列

  1. test_user
    id->主列
    用户名

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']);
}

}

Model 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'));
}

1 回答

  • 0

    添加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'));
    
    }
    

相关问题