9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel の Relation でCreateManyはバルクインサートしているわけではない

9
Posted at

ただの確認不足だったのですが
クエリめっちゃ発行されるなと思い場所をたどったところ
リレーションしている、1:多の子のinsertにcreateManyを使っていた場所でした。

createManyメソッドで複数のリレーションモデルを生成することができます。

$post = App\Post::find(1);

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

insert into `comments` (`message`, `post_id`, `updated_at`, `created_at`) values ('A new comment.', 1, '2019-11-14 16:48:49', '2019-11-14 16:48:49')

insert into `comments` (`message`, `post_id`, `updated_at`, `created_at`) values ('Another new comment.', 1, '2019-11-14 16:48:49', '2019-11-14 16:48:49')

HasOneOrMany
    /**
     * Attach a model instance to the parent model.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return \Illuminate\Database\Eloquent\Model|false
     */
    public function save(Model $model)
    {
        $this->setForeignAttributesForCreate($model);

        return $model->save() ? $model : false;
    }

    /**
     * Create a new instance of the related model.
     *
     * @param  array  $attributes
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function create(array $attributes = [])
    {
        return tap($this->related->newInstance($attributes), function ($instance) {
            $this->setForeignAttributesForCreate($instance);

            $instance->save();
        });
    }

    /**
     * Create a Collection of new instances of the related model.
     *
     * @param  iterable  $records
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function createMany(iterable $records)
    {
        $instances = $this->related->newCollection();

        foreach ($records as $record) {
            $instances->push($this->create($record));
        }

        return $instances;
    }

createManycreateを呼び出し、結果をコレクションに入れています。
createではsaveを呼び出し...

バルクインサートできるものと思って使っていたのですが、やはり一括でやりたい場合はinsertなのでしょうかね

とはいえ、この手のクエリがほかのより以上に速いのはなぜなのでしょう...400μsくらいなんですよね

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?