duanpacan9388 2016-06-15 20:58
浏览 177

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

Hello to everyone out there I am new to 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. 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
        id->first column
        role_name->second column

2. test_user
        id->primary column
        user_name

3.user_role
        id->primary key
        user_id ->foreign key(primary key of test_user)
        role_id ->foreign key(primary key of 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

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

Below are the controllers 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

 <?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

   <?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

   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条回答 默认 最新

  • dongquanyu5816 2016-06-16 04:30
    关注

    Add in TestRole model

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

    Add in TestUser model

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c