gamedev
gamedev

Reputation: 97

laravel scout add additional attribute (only in meilisearch)

I try to migrate a SQL based search to meilisearch using laravel scout.

At the moment the whole search should be migrated to meilisearch, including all filter and sorting options.

A product has a relation to feedbacks (product model):

//returns all feedbacks for the product
public function allFeedbacks()
{
    return $this->hasMany('App\Models\Feedback');
}

I would like to include the amount of feedbacks to meilisearch, but not the whole relation, since it's not required for sorting.

How can I add additional fields to be index by meilisearch, without including a field into the mySQL database (feedback_amount f.e.)?

Upvotes: 0

Views: 1107

Answers (1)

whit
whit

Reputation: 26

In Product.php:

public function toSearchableArray() {
  $fields = [
    'feedback_amount' => $this->allFeedbacks()->count(),
    'price' => $this->price,
    'other_stuff' => $this->other_stuff
  ];

  return $fields;
}

Then flush and import the model again.

This will override the parent toSearchableArray() so you will want to include any other fields you want searchable.

Upvotes: 1

Related Questions