Answer the question
In order to leave comments, you need to log in
Properly saving models with linked Yii2 data?
There are two tables
1. Atricles [articles]
2. Authors [authors]
3. Articles_Authors [article_id author_id]
There is a many to many relationship between them with ids from the first table and the second.
What are the practices (without third-party extensions) for saving links in table 3.
How to implement saving data, taking into account the fact that I get data from an XML file when parsing?
At the moment, the import of articles is implemented:
foreach ($fileXML->issue->articles->article as $articleFromXML) {
$articleForImport = new Articles();
$articleForImport->ydk_code = strval($articleFromXML->codes->udk);
$articleForImport->header = strval($articleFromXML->artTitles->artTitle);
$articleForImport->annotation = strval($articleFromXML->abstracts->abstract);
foreach ($articleFromXML->keywords->kwdGroup as $keyWords) {
$forImplode = (array)$keyWords->keyword;
$keyWordsForImport = implode(', ', $forImplode);
$articleForImport->keywords = $keyWordsForImport;
}
$articleForImport->fk_issue = $issue->id;
if ($articleForImport->validate()) {
$articleForImport->save();
}
foreach ($articleFromXML->authors->author as $authorFromXML) {
$authorForImport = new Authors();
$authorForImport->surname = (string)$authorFromXML->individInfo->surname;
$authorInitials = explode(" ", $authorFromXML->individInfo->initials);
$authorForImport->name = $authorInitials[0];
$authorForImport->patronymic = $authorInitials[1];
$authorForImport->orgName = (string)$authorFromXML->individInfo->orgName;
$authorForImport->contactInfo = (string)$authorFromXML->individInfo->email;
$authorForImport->additionalInfo = (string)$authorFromXML->individInfo->otherInfo;
if ($authorForImport->validate()) {
$authorForImport->save();
}
}
$ArticlesAuthors = new ArticlesAuthors
....
ArticlesAuthors->save();
Answer the question
In order to leave comments, you need to log in
The hardest part is understanding how models work for persisting related data in Yii2.
$article = new Article( [ ... ] );
$article->save();
$author = new Author( [ ... ] );
$author->save();
$article2Author = new ArticleAuthor( [
'article_id' => $article->id,
'author_id' => $author->id,
] );
$article2Author->save();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question