S
S
Sergey Khlopov2019-10-14 13:42:29
Laravel
Sergey Khlopov, 2019-10-14 13:42:29

How to reduce the number of queries in polymorphic one-to-many relationships?

Hello, please tell me, I have the following method:

public static function contentSetImages(Category $category, $paths)
    {
        $images = [];
        foreach ($paths as $path) {
            $images[] = Image::create(['src' => $path]);
        }
        $category->images()->saveMany($images);
    }

It adds pictures to the database and then associates the added pictures with the corresponding category, as a result, this method makes 2 requests for one added picture. Can you please tell me how to reduce the number of queries to the database?
Screenshot of requests below
5da450f191478744525677.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Kulaxyz, 2019-10-14
@Shlop

Reduce by 2 times.

public static function contentSetImages(Category $category, $paths)
    {
        $images = [];
        foreach ($paths as $path) {
           $category->images()->create(['src' => $path]);
    }
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question