使用insert()并进行批量插入似乎不会触发带有侦察到Algolia的插入

时间:2018-01-23 18:47:00

标签: laravel laravel-5 laravel-scout

我在Laravel中进行批量插入,如

\App\Example::insert([
    [
        'name' => 'abc',
        'value' => '123',
    ],
    [
        'name' => 'def',
        'value' => '456',
    ],
    // etc...
]);

这将执行批量插入,一次查询但仍然一次插入多行。

问题在于,当我使用insert()时,行不会插入到Algolia中。那么我怎样才能批量插入Algolia呢?

我不想循环遍历我的行并逐个插入,因为这会花费额外的请求

2 个答案:

答案 0 :(得分:1)

您可以在模型集合上调用->searchable(),如@Ohgodwhy在评论中提到的那样。 Scout的Algolia引擎将批量处理多个模型实例的更新,从而使请求的总数保持较低。

答案 1 :(得分:1)

The problem is that Laravel Scout creates the Algolio Searchable on the model::created method.

You can view that here in the source code.

As Laravel does not spawn the created/updated/deleted events on Mass Events this means that Algolio will never receive these as well.

One option to work around this would be to take the most recent auto-incrementing ID, then after the insert take that ID again, then call ->searchable() on a filtered where clause on the relationship, like this:

 DB::transaction(function() {
    $currentId = \App\Example::max('id');
    // do the insert
    $lastId = \App\Example::max('id');

    \App\Example::where('id', '>', $currentId)->where('id', '<=', $lastId)->searchable();
 });

By using a transaction we ensure that we the $lastId wouldn't be corrupted by parallel queries. In this way, we have to perform 4 queries, which is still nominal compared to possibly dozens or more.

Truthfully you could probably simplify that code more.