как связать три таблицы на yii2 php

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

как связать три таблицы на yii2 php

Сообщение Arta »

Здравствуйте,уважаемые пользователи этого форума подскажите пожайлусто как мне сделать так чтобы можно было связать три таблици из которых с одной в другую будет подгружаться добавленая информация к примеру - каталог сериалов в одной таблице добавил сериал в другой сезон сериалов в третей эпизод и чтобы после добавления сериала при добавлении сезона подгружалось название сериала в категорию сезон,после добавления сезона в категорию эпизод добавлялось количество сезонов как связать эти три таблици подскажите пожайлуста - какие сбросить файлы для просмотра чтобы можно было мне подсказать ??? за много заданых вопросов извините но я не профосионал - новичок.....
geee
Сообщения: 18
Зарегистрирован: 2017.02.19, 18:20

Re: как связать три таблицы на yii2 php

Сообщение geee »

Для начала нужно определить структуру БД, как одна таблица связана с другой (по каким полям), какие поля есть в этих таблицах и т.д, и написать эту структуру здесь. Так сложно что-то понять из вопроса.
Arta
Сообщения: 41
Зарегистрирован: 2016.10.26, 11:08

Re: как связать три таблицы на yii2 php

Сообщение Arta »

Вот форма Category отвечающая за Добавления сериалов

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

<?php

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

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

<div class="category-form">

  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
  
   <?= $form->field($model, 'id')->textInput() ?>
	
    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'names')->textInput(['maxlength' => true]) ?>
	
	<?= $form->field($model, 'file')->fileInput() ?>
	
	<?= $form->field($model, 'opis')->textarea(['rows' => 6]) ?>
	
    <?= $form->field($model, 'janr')->textInput() ?>
	
    <?= $form->field($model, 'god')->dropDownList($model->getGod()) ?>

    <?= $form->field($model, 'start')->dropDownList($model->getStart()) ?>

    <?= $form->field($model, 'end')->dropDownList($model->getEnd()) ?>

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

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>
После добавления сериала в таблице sezon вот её форма в поле выпадающем списком serial чтобы был выведен добавлен сериал.

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

<?php

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

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

<div class="sezon-form">

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

    <?= $form->field($model, 'serial')->dropDownList(
			ArrayHelper::map($sezon, 'id', 'name')
		) ?>
   
   <?= $form->field($model, 'number')->textInput() ?>

    <?= $form->field($model, 'seriy')->dropDownList($model->getSeriy()) ?>

    <?= $form->field($model, 'start')->dropDownList($model->getStart()) ?>

    <?= $form->field($model, 'end')->dropDownList($model->getEnd()) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

После этого допустим нужно добавить эпизод чтобы подгружались сезоны вот форма этой таблици.

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

<?php

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

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

<div class="epizod-form">

    <?php $form = ActiveForm::begin(); ?>
	
	
	
        <?= $form->field($model, 'sezon')->dropDownList(
			ArrayHelper::map($sezon, 'id', 'name')
		) ?>

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

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

    <?= $form->field($model, 'opis')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'nomer')->dropDownList($model->getNomer()) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

это формы этих таблиц вот их модели модель Category.

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

<?php

namespace app\module\admin\models;

use Yii;
use yii\web\UploadedFile;
/**
 * This is the model class for table "category".
 *
 * @property integer $id
 * @property string $name
 * @property string $names
 * @property string $janr
 * @property string $opis
 * @property integer $god
 * @property integer $start
 * @property integer $end
 * @property string $status
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
	public $file;
	
    public static function tableName()
    {
        return 'category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            
            [['id'], 'required'],
            [['id', 'god', 'start', 'end'], 'integer'],
            [['opis'], 'string'],
            [['file'], 'file'],
            [['name', 'names', 'janr', 'status'], 'string','max' => 255],
          
        ];
    }
    /**
     * @return \yii\db\ActiveQuery
    public function getEpizod()
    {
        return $this->hasOne(Epizod::className(), ['sezon' => 'id']);
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
		    'id' => 'ID',
            'name' => 'Название',
            'names' => 'Орегинальное название',
			'file' => 'Постер',
            'janr' => 'Жанр',
            'opis' => 'Описание',
            'god' => 'Год выпуска',
            'start' => 'Начало периода',
            'end' => 'Конец периода',
            'status' => 'Статус',
	];
	}
		    public function getJanr()
    {
		$janr = [];
		for ($i = 2017; $i > 1989; $i--) {
			$janr[$i] = $i;
		}
		
        return $janr;
    }
	
    public function getGod()
    {
		$god = [];
		for ($i = 2017; $i > 1989; $i--) {
			$god[$i] = $i;
		}
		
        return $god;
    }
	    public function getStart()
    {
		$start = [];
		for ($i = 2017; $i > 1989; $i--) {
			$start[$i] = $i;
		}
		
        return $start;
    }
	    public function getEnd()
    {
		$end = [];
		for ($i = 2017; $i > 1989; $i--) {
			$end[$i] = $i;
		}
		
        return $end;
    }
	
	    public function getStatus()
    {
		$end = [];
		for ($i = 2017; $i > 1989; $i--) {
			$end[$i] = $i;
		}
		
        return $end;
    }
}
Модель Sezon

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

<?php

namespace app\module\admin\models;

use Yii;

/**
 * This is the model class for table "sezon".
 *
 * @property integer $id
 * @property string $serial
 * @property integer $number
 * @property integer $seriy
 * @property integer $start
 * @property integer $end
 */
class Sezon extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sezon';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'required'],
            [['id', 'number', 'seriy', 'start', 'end'], 'integer'],
            [['serial'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'serial' => 'Сериал',
            'number' => 'Номер',
            'seriy' => 'Серий',
            'start' => 'Начало периода',
            'end' => 'Конец периода',
        ];
    }
	 public function getSeriy()
    {
		$seriy = [];
		for ($i = 1; $i < 100; $i++) {
			$seriy[$i] = $i;
		}
		
        return $seriy;
    }
	
		    public function getStart()
    {
		$start = [];
		for ($i = 2017; $i > 1989; $i--) {
			$start[$i] = $i;
		}
		
        return $start;
    }
			    public function getEnd()
    {
		$end = [];
		for ($i = 2017; $i > 1989; $i--) {
			$end[$i] = $i;
		}
		
        return $end;
    }
}
Модель Epizod

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

<?php

namespace app\module\admin\models;

use Yii;

/**
 * This is the model class for table "epizod".
 *
 * @property integer $id
 * @property integer $sezon
 * @property string $name
 * @property string $names
 * @property string $opis
 * @property integer $nomer
 */
class Epizod extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'epizod';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'sezon', 'nomer'], 'integer'],
            [['opis'], 'string'],
            [['name', 'names'], 'string', 'max' => 255],
        ];
    }
	 /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sezon' => 'Сезон',
            'name' => 'Название',
            'names' => 'Орегинальное название',
            'opis' => 'Описание',
            'nomer' => 'Номер',
        ];
  }
 public function getNomer()
    {
		$nomer = [];
		for ($i = 1; $i < 100; $i++) {
			$nomer[$i] = $i;
		}
		
        return $nomer;
    }
}
Вот их контроллеры

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

<?php

namespace app\module\admin\controllers;

use Yii;
use app\module\admin\models\Category;
use app\module\admin\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

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

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

    /**
     * Displays a single Category model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Category();
            
		if ($model->load(Yii::$app->request->post()) && $model->save()){
           /* $model->file=UploadedFile::getInstance($model,'file');
            $model->file->saveAs('uploads/'. $model->file->baseName .'.'.$model->file->extension);
            
            $model->foto = 'uploads/'.$model->file->baseName .'.'.$model->file->extension;
			*/
            $model->created-date('Y-m-d h:m:s');
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Category 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 Category 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 Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Sezon

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

<?php

namespace app\module\admin\controllers;

use Yii;
use app\module\admin\models\Sezon;
use app\module\admin\models\SezonSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

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

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

    /**
     * Displays a single Sezon model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Sezon model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Sezon();

        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 Sezon 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 Sezon 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 Sezon model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Sezon the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Sezon::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Epizod

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

<?php

namespace app\module\admin\controllers;

use Yii;
use app\module\admin\models\Epizod;
use app\module\admin\models\EpizodSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

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

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

    /**
     * Displays a single Epizod model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Epizod model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Epizod();

        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 Epizod 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 Epizod 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 Epizod model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Epizod the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Epizod::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Подскажите пожайлусто как сязать эти таблици чтобы получить такой результат, что нужно изменить и как правильно это сделать - помогите мне в этом разобраться???
Ответить