Сохранение данных многие ко многим

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

Сохранение данных многие ко многим

Сообщение scream »

Всем доброго времени суток! Есть связь многие ко многим через промежуточную таблицу.
Схема http://piccy.info/view3/10984428/23047f ... 418997c88/

Как мне сохранить данные в таблицы Artist и Place_Artist из формы? Заранее спасибо!

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

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "Artist".
 *
 * @property integer $idArtist
 * @property string $name
 * @property string $description
 * @property string $date_concert
 *
 * @property PlaceArtist[] $placeArtists
 * @property Place[] $placeIdPlaces
 */
class Artist extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'Artist';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['description'], 'string'],
            [['date_concert'], 'safe'],
            [['name'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'idArtist' => 'Id Artist',
            'name' => 'Name',
            'description' => 'Description',
            'date_concert' => 'Date Concert',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPlaceArtists()
    {
        return $this->hasMany(PlaceArtist::className(), ['Artist_idArtist' => 'idArtist']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPlaceIdPlaces()
    {
        return $this->hasMany(Place::className(), ['idPlace' => 'Place_idPlace'])->viaTable('Place_Artist', ['Artist_idArtist' => 'idArtist']);
    }
}
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "Artist".
 *
 * @property integer $idArtist
 * @property string $name
 * @property string $description
 * @property string $date_concert
 *
 * @property PlaceArtist[] $placeArtists
 * @property Place[] $placeIdPlaces
 */
class Artist extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'Artist';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['description'], 'string'],
            [['date_concert'], 'safe'],
            [['name'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'idArtist' => 'Id Artist',
            'name' => 'Name',
            'description' => 'Description',
            'date_concert' => 'Date Concert',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPlaceArtists()
    {
        return $this->hasMany(PlaceArtist::className(), ['Artist_idArtist' => 'idArtist']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPlaceIdPlaces()
    {
        return $this->hasMany(Place::className(), ['idPlace' => 'Place_idPlace'])->viaTable('Place_Artist', ['Artist_idArtist' => 'idArtist']);
    }
}

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

<?php

namespace app\controllers;

use app\models\Place;
use app\models\PlaceArtist;
use Yii;
use app\models\Artist;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

    /**
     * Lists all Artist models.
     * @return mixed
     */
    public function actionIndex()
    {
        $artist = new Artist();
        $place = $artist->placeIdPlaces;
        $dataProvider = new ActiveDataProvider([
            'query' => Artist::find(),
        ]);

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

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

    /**
     * Creates a new Artist model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Artist();
        $place = new Place();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->idArtist]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'place' => $place,
            ]);
        }
    }

    /**
     * Updates an existing Artist 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->idArtist]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

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

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

<?php

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

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

<div class="artist-form">

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

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

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

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

<!--    --><?//= $form->field($model->placeIdPlaces, 'address')->label('Address')->dropDownList(\app\models\PlaceArtist::find()->select(['Place_idPlace'])->column(),
//        ['prompt'=>'Select Place']) ?>

    <?= $form->field($model, 'placeIdPlaces')->label('Address')->dropDownList(\yii\helpers\ArrayHelper::map(\app\models\PlaceArtist::find()->all(),'place.idPlace','place.address')) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

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

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "Place_Artist".
 *
 * @property integer $Place_idPlace
 * @property integer $Artist_idArtist
 *
 * @property Artist $artistIdArtist
 * @property Place $placeIdPlace
 */
class PlaceArtist extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'Place_Artist';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Place_idPlace', 'Artist_idArtist'], 'required'],
            [['Place_idPlace', 'Artist_idArtist'], 'integer'],
            [['Artist_idArtist'], 'exist', 'skipOnError' => true, 'targetClass' => Artist::className(), 'targetAttribute' => ['Artist_idArtist' => 'idArtist']],
            [['Place_idPlace'], 'exist', 'skipOnError' => true, 'targetClass' => Place::className(), 'targetAttribute' => ['Place_idPlace' => 'idPlace']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'Place_idPlace' => 'Place Id Place',
            'Artist_idArtist' => 'Artist Id Artist',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getArtist()
    {
        return $this->hasOne(Artist::className(), ['idArtist' => 'Artist_idArtist']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPlace()
    {
        return $this->hasOne(Place::className(), ['idPlace' => 'Place_idPlace']);
    }
}
Ответить