function runBookInsertion($i) { $book = new Book(); $book->title = 'Hello' . $i; $book->isbn = '1234'; $book->price = $i; //$book->author_id = $this->authors[array_rand($this->authors)]->id; $book->link('author', $this->authors[array_rand($this->authors)]); $book->save(false); $this->books[] = $book; }
/** * Сохраняет модель и связанные данные * * @param Book $modelBook * @return \yii\web\Response */ private function _saveBook(Book $modelBook) { $authorIds = Yii::$app->request->post('authors'); $tagIds = Yii::$app->request->post('tags'); if ($modelBook->load(Yii::$app->request->post()) && $modelBook->save()) { array_map(function ($model) use($modelBook) { $modelBook->unlink('authors', $model, true); }, $modelBook->authors); foreach ($authorIds ?: [] as $authorId) { /** @var Author $modelAuthor */ $modelAuthor = Author::findOne($authorId); $modelBook->link('authors', $modelAuthor); } array_map(function ($model) use($modelBook) { $modelBook->unlink('tags', $model, true); }, $modelBook->tags); foreach ($tagIds ?: [] as $tagId) { /** @var Tag $modelTag */ $modelTag = Tag::findOne($tagId); $modelBook->link('tags', $modelTag); } return $this->redirect(['back-book/view', 'id' => $modelBook->id]); } }