Yii 2.0: Working with relational removals by yii2

2 followers

This tutorial shows you how to safely remove records between relationships.

First we create three tables using a Many to Many relationship.

Imagem da relacao

** Important: Apply cascade to foreign key constraints for update and delete. **

The cascade feature will allow you to remove the foreign keys along with the line you want to delete and helps keep your code to a minimum.

Script SQL the ralation has.

CREATE TABLE `tests_has_games` (
   `tests_id` int(11) NOT NULL,
   `games_id` int(11) NOT NULL,
   PRIMARY KEY (`tests_id`,`games_id`),
   KEY `fk_tests_has_games_games1_idx` (`games_id`),
   KEY `fk_tests_has_games_tests_idx` (`tests_id`),
   CONSTRAINT `fk_tests_has_games_games1` FOREIGN KEY (`games_id`) REFERENCES `games` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
   CONSTRAINT `fk_tests_has_games_tests` FOREIGN KEY (`tests_id`) REFERENCES `tests` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin

Step 2: Create models: (to use generator gii, this system create model with relations of the table). ** ModelGames: **

public function getTestsHasGames()
    {
        return $this->hasMany(TestsHasGames::className(), ['games_id' => 'id']);
    }
 
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTests()
    {
        return $this->hasMany(Tests::className(), ['id' => 'tests_id'])->viaTable('{{%tests_has_games}}', ['games_id' => 'id']);
    }

** Model Tests: **

public function getTestsHasGames()
    {
        return $this->hasMany(TestsHasGames::className(), ['tests_id' => 'id']);
    }
 
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGames()
    {
        return $this->hasMany(Games::className(), ['id' => 'games_id'])->viaTable('{{%tests_has_games}}', ['tests_id' => 'id']);
    }

Step 3: Simple Removal Functions in controllers:

public function actionDeletarTest($id)
  {
 
    $session = \Yii::$app->session;
 
    $testes = Tests::findOne($id);
 
    if($testes->delete())
    {
      $session->addFlash('resposta', [
        'type'=>'success',
        'msg'=>'Teste deletado com sucesso.'
      ]);
    }else{
      $session->addFlash('resposta', [
        'type'=>'danger',
        'msg'=>'Erro encontrado favor resolver.'
      ]);
    }
 
    return $this->redirect(['site/delete-relations']);
 
  }

Other Methods

public function actionDeleteListGames()
  {
    $array_id = [1,2,3,4];
 
    $games = Games::find()->where(['in','id',$array_id])->all();
 
    foreach($games as $k => $game)
    {
      $game->delete();
    }
 
  }
     // deletando de vinculo
     public function actionDeleteTestAll()
     {
       $game = Games::findOne(1);
       foreach($game->tests as $test)
       {
          $test->delete();
       }
     }
 
 
public function actionDeleteTheRelation($id)
  {
 
 
    $game = Games::find()->joinWith(['tests'=>function($q){
      return $q->where(['like','nome','proccess'])
    }])->where(['id'=>$id])->one();
 
    foreach($games->tests as $k => $test)
    {
      $test->delete();
    }
 
  }

Get All code in Your text to link here...

Total 2 comments

#20084 report it
Jairus Martin at 2017/06/05 12:01am
It is a good start.

It is a nice start AndroideLP, maybe a little confusing with the jump between Spanish and English. I made some minor adjustments for clarity in the beginning.

#20078 report it
AndroideLP at 2017/05/11 04:53pm
Comments are welcome

I need to know if the wiki is well explained so I can improve the next posts.

Leave a comment

Please to leave your comment.