Hi everybody,
i’m new in yii2 and i’m just becoming mad about many to many relations.
Consider one model Author and one model Book, one author can write multiple books, and a book can be write by multiple authors.
Ok story short.
In model book i have:
public function getAuthors() {
return $this->hasMany(Autori::className(), ['id' => 'id_autore'])->viaTable('tbl_r_libriautori', ['id_libro' => 'id']);
}
I have a simple junction table with foreign key for books and authors.
Ok the problem is. When i create new book in controller i have:
if ($model->load(Yii::$app->request->post()) && $model->save()) {
...
...
for ($i = 0; $i < count($arrayauthors); $i++) {
$model_autore = \common\models\Autori::findOne($arrayautori[$i]);
$model->link('authors', $model_autore);
}
Ok the link() call correctly populate the junction table but it save the model book again. After the call to book/create controller, i have 2 books and 4 entry in junction table.
It’s supposed to call only link and not save() ? If i need then to update just to add an author to a book how can i populate junction table without re-save the book if link auto re-save? Is there a way to just populate junction table? I mean with link , offcourse i can just make new EntryJunctionTable then set id and save it, but i just to try understand yii2. Thank for read till this point and for answers.
Bye.