H
H
Hancock_8882016-06-30 08:50:46
Yii
Hancock_888, 2016-06-30 08:50:46

How to save 100 articles and 200 related pictures in two requests in Yii2?

Good day to all. Whether prompt probably to save 300 records for two requests to basis.
For example, there are two tables: articles and pictures for them.
article
----------------------
id
title
description
article_image
---------------------- -
id
article_id
name
I receive an array of articles and links to pictures.

$articles = [
            'article_1' => [
                'title' => 'Title 1',
                'description' => 'text 1',
                'images' =>['name1.jpg','name2.jpg']
            ],
            'article_2' => [
                'title' => 'Title 2',
                'description' => 'text 2',
                'images' =>['name3.jpg','name4.jpg']
            ], // ...
        ];

I have already mastered the multiple saving of pictures in one request,
I run through the array of articles and generate an array of pictures and then save.
\Yii::$app->db
            ->createCommand()
            ->batchInsert('article_image', ['article_id', 'name'], [
                [1, 'name1.jpg'],
                [2, 'name2.jpg'],
                [3, 'name3.jpg'],
            ])
            ->execute();

Those. now
I have 101 requests to the database:
100 requests to save articles
and 1 request to save pictures.
How it is possible to save for 2 requests? The problem is that when saving images, you need an article_id, which can only be obtained when saving the article.
Or tell me how you solve the issue of optimizing queries to the database with multiple saves?
I came up with one way how to save 100 articles 200 pictures in 3 requests
1. the first request saves 100 articles with a unique number (a new unique_number column has been added, and I generate it myself and save it to an array)
2 . the second request I do the extraction of 100 unique_numbers that I just generated, I get the Ids of the articles, I convert the
unique_number -> id
3. I save 200 pictures in one request

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2016-06-30
@Hancock_888

the only option is to select max(id) from the article, lock the table, manually add ids starting from the maximum, insert, then unlock the table.
The solution is not very normal, because. "breaks" the normal operation of autoincrement, which is not good. But it will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question