使用 Laravel Scout 时,Searchable() 不会更新相关模型



我在使用侦察弹性搜索更新相关模型时遇到问题。

$event->priceranges()->delete();
$event->priceranges()->Create([
'price' => $ticket['ticket_price']
]);
$event->update([ 
'show_times' => $request->showtimes,
]);
$event->searchable();

在我的数据库中,我看到了事件和价格范围表的更新。然而,当我查看我的弹性搜索数据时,只有事件的数据得到了更新。任何相关模型都不会更新。

如果我对模型和价格范围模型进行第二次更新,那么弹性搜索数据会显示我第一次更新的数据(对于相关模型,它总是落后一次更新(我试着做

$event->pricerange->searchable()

但给了我一个错误,因为我没有价格范围的可搜索索引,我只是使用我的事件模型及其关系来索引。除了searchable((之外,还有什么方法可以强制更新吗?

看起来您的关系正在Event模型索引中进行索引,对吗?

可能它没有被更新,因为关系已经加载,并且Laravel没有更新已经加载的关系数据,例如:

$event = Event::with('priceranges')->first()
var_dump($event->priceranges->count()): // outputs for example 5
$event->priceranges()->create([...]);
var_dump($event->priceranges->count()): // still outputs 5, meaning that the created pricerange is not loaded

因此,要解决此问题,可以在调用searchable():之前重新加载模型

$event = $event->fresh();
$event->searchable();

但是,请注意,每次更新时,都会调用可搜索方法,因此每次更新时都会对其进行两次索引。

因此,您也可以在返回数据之前更新Event模型中的toSearchableArray()方法以获得新的模型(我假设您使用的是babenkoivan/scout-elasticsearch-driver(。

最新更新