Is it possible with Gii to generate a CRUD from DB tables with relationships?

Example tables:

author

id name // имя автора 

book

 id title // название книги author_id // id автора из таблицы author 

SQL

 CREATE TABLE author ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL ) ENGINE = InnoDB; CREATE TABLE book ( id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200) NOT NULL, author_id SMALLINT UNSIGNED NOT NULL, CONSTRAINT `fk_book_author` FOREIGN KEY (author_id) REFERENCES author (id) ON DELETE CASCADE ON UPDATE RESTRICT ) ENGINE = InnoDB; 

Gii generates a method in the Author model; getBooks () method

  public function getBooks() { return $this->hasMany(Book::className(), ['author_id' => 'id']); } 

I understand correctly that with the help of this method you can display the author’s book in view? (if not, you can link to the example)

And the second question: How to create a CRUD from this structure of the database tables in YII2 so that when adding a book you can choose author_id instead of author_id. I mean automated methods (if such exist) so that he from the relation understands that it is necessary to generate a model and CRUD based on the relations.

  • Clarify the question. Do you want to immediately generate two models with links? Standard functionality, if you do not take third-party extended ships, suggests setting links when generating a model using foreign keys of tables in a database. - white-imp
  • Manual models, and CRUD based on these two models. - noc

1 answer 1

I understand correctly that with the help of this method you can display the author’s book in view?

Yes, you can output all these books using the $model->books variable through foreach , where $model is the model Author

How to create a CRUD from this structure of the database tables in YII2 so that when adding a book you can choose author_id instead of author_id.

You cannot do this through relation because there is no connection yet, you are only creating a book. Therefore, it is done like this:

Controller

 public function actionCreate() { $model = new Book(); $authors = Author::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, 'authors' => $authors ]); } } 

View

 use yii\helpers\ArrayHelper; <?= $form->field($model, 'author_id')->dropDownList(ArrayHelper::map($authors, 'id', 'name'))->label('Выберите имя автора'); ?>