Проблема при сохранении. Связь многие к многим

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Cepairda
Сообщения: 17
Зарегистрирован: 2017.06.27, 17:51

Проблема при сохранении. Связь многие к многим

Сообщение Cepairda »

Всем привет) У меня есть таблица teachers(преподаватели ), таблица subjects(предметы) и таблица teachers_subjects(промежуточная таблица).
Мне нужно использовать связь многие ко многим. Но тут и возникает проблема.
Для создания CRUD я использовал Gii. Но он сам видимо не умеет создать формы для работы со связанными таблицами.
Поэтому я подправил код.
В форме добавления преподавателей я добавил поле Предметы(Выводятся предметы из таблицы Предметы), там выводятся все предметы в виде чекбоксов. Собственно в этом и проблема, как сделать чтобы выбранные чекбоксы записывались в промежуточную таблицу ?
В данный момент после сохранения сохраняются только данные в таблицу Teachers, но как сделать, чтобы в промежуточную таблицу добавлялась запись ? Помогите пожалуйста :(

Модель Teachers

Код: Выделить всё

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Teachers extends ActiveRecord
{
    public static function tableName()
    {
        return 'teachers';
    }
    
    public function getSubjectsId()
    {
        return $this->hasMany(Subjects::className(), ['id' => 'subjects_id'])
            ->viaTable('teachers_subjects', ['teachers_id' => 'id']);
    }
 }
Контроллер Teachers

Код: Выделить всё

<?php

namespace app\controllers;

use Yii;
use app\models\Teachers;
use app\models\TeachersSearch;
use app\models\Departments;
use app\models\Posts;
use app\models\Subjects;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

/**
 * TeachersController implements the CRUD actions for Teachers model.
 */
class TeachersController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Teachers models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TeachersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Teachers model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $teacher = Teachers::findOne($id);
        $departmentName = $teacher->departmentIdName;
        
        //die($departmentName);
        //die($departmentName);
        
        $postName = $teacher->postIdName;
        
        //die($postName);
        
        return $this->render('view', [
            'model' => $this->findModel($id),
            'departmentName' => $departmentName,
            'postName' => $postName,
        ]);
    }

    /**
     * Creates a new Teachers model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Teachers();
        
        $subjects = Subjects::find()->all();
        
        $department = new Departments();
        $facultiesWithDepartment = $department->find()->with('facultyId')->asArray()->all();
        $posts = Posts::find()->all();
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'facultiesWithDepartment' => $facultiesWithDepartment,
                'posts' => $posts,
                'subjects' => $subjects
            ]);
        }
    }

    /**
     * Updates an existing Teachers 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);
        $department = new Departments();
        $facultiesWithDepartment = $department->find()->with('facultyId')->asArray()->all();
        $posts = Posts::find()->all();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'facultiesWithDepartment' => $facultiesWithDepartment,
                'posts' => $posts,
            ]);
        }
    }

    /**
     * Deletes an existing Teachers 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 Teachers model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Teachers the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Teachers::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\Teachers */

$this->title = 'Create Teachers';
$this->params['breadcrumbs'][] = ['label' => 'Teachers', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="teachers-create">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= $this->render('_form', [
        'model' => $model,
        'facultiesWithDepartment' => $facultiesWithDepartment,
        'posts' => $posts,
        'subjects' => $subjects,
    ]) ?>

</div>

И _form.php

Код: Выделить всё

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;

/* @var $this yii\web\View */
/* @var $model app\models\Teachers */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="teachers-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'surname')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'patronymic')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'post')->dropDownList(ArrayHelper::map($posts, 'id', 'name'), ['options' => [$model->post => ['Selected'=>'selected']]])  ?>

    <?= $form->field($model, 'degree')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'rank')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'load')->textInput() ?>

    <?= $form->field($model, 'departments')->dropDownList(ArrayHelper::map($facultiesWithDepartment, 'id', 'name',
        function($facultiesWithDepartment, $defaultValue) {
            return 'Факультет - ' . $facultiesWithDepartment['facultyId']['name'];
        }), ['options' => [$model->departments => ['Selected'=>'selected']]]) 
    ?>
    
    <?= $form->field($model, 'subjectsId')->checkboxList(ArrayHelper::map($subjects, 'id', 'name')) ?>
    
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
Ответить