laravelelasticsearchlaravel-scout

makeAllSearchableUsing doesn't work to eagerload relation with elasticsearch


I have the following code in my Laravel 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');
}

I am using Explorer with Laravel Scout and I have both flushed and imported the data.

When I run the query Model::search('fish')->field('name')->get(), the output only contains this data:

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

However, I expect to get the users relation data which looks like this:

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

or add the relation of $query->withCount('users'); and sort by it.

What is causing this problem?

This is my model of 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);
}

and my explorer.php has

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

Solution

  • You have to include the users relationship in the toSearchableArray method:

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