You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

makeAllSearchableUsing无法预加载关联数据至Elasticsearch问题排查

问题:Laravel Scout + Explorer 无法返回关联模型数据及withCount排序问题

背景与涉及代码

我使用Laravel Scout搭配Explorer,已执行数据清空与导入操作,相关代码如下:

主模型(Model)代码

public function toSearchableArray() {
    return [
        'name' => $this->name,
        'description' => $this->description,
    ];
}

public function mappableAs(): array {
    return [
        'name' => 'text',
        'description' => 'text',
    ];
}

public function makeAllSearchableUsing($query) {
    return $query->with('users');
}

public function users() {
    return $this->belongsToMany(User::class, 'users');
}

User模型代码

public function toSearchableArray(): array {
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
    ];
}

public function mappableAs(): array {
    return [
        'id' => 'integer',
        'name' => 'text',
        'email' => 'text',
    ];
}

public function models($owner = true) {
    return $this->hasMany(Model::class);
}

explorer.php配置

'indexes' => [
    Model::class,
    User::class,
],

问题现象

执行查询Model::search('fish')->field('name')->get()后,返回结果仅包含基础字段:

id: 1,
name: "Ea nemo fish unde esse",
description: "Tempore nihil cumque eum quo"

但我期望返回关联的users数据(如下),或实现添加$query->withCount('users');并按其排序:

users: {
  {id: 1, name: 'User1'},
  {id: 2, name: 'User2'},
}

问题原因

  • 关联数据未存入搜索索引:makeAllSearchableUsing仅在数据导入时预加载关联,但Scout/Explorer最终存入索引的是toSearchableArray返回的数据。你的toSearchableArray未包含users关联信息,所以索引中没有该数据,查询自然无法返回。
  • 多对多关联关系定义错误:Model的users()方法中,第二个参数'users'是User模型的表名,不符合Laravel多对多中间表的命名约定(应为model_user这类交叉表名),这会导致预加载关联本身失败,即使索引存了数据也无法正确关联。
  • withCount无法直接用于搜索排序:withCount('users')是Eloquent的查询逻辑,而Scout搜索基于索引执行。要实现按用户数量排序,需要将users_count字段加入toSearchableArray和mappableAs,同步到索引后才能在搜索时使用该字段排序。

内容的提问来源于stack exchange,提问作者fjduqrllhdnolvgrcc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:27:48