Reputation: 11
I'm playing around with Scout and MeiliSearch in Laravel 8 and struggling a little with searching related attributes. I have an adverts table, an attributes table (e.g. colour, size, etc.) and an attribute_options table (e.g. black, blue, yellow, sm, m, xl, etc.). An Attribute hasMany AttributeOptions. An Advert can have many Attributes and an Attribute can belongToMany Adverts so there's a pivot table advert_attribute to handle that relationship. The pivot table includes an extra column attribute_option_id, to relate the specific Attribute option to the Advert. I have a method getAdvertAttributes which returns the values of each of the attributes associated with an Advert.
In the Advert model I''m using toSearchableArray to customise the properties of my model that are indexed. As part of this I loop through the attributes and create a new entry for each attribute title. An indexed ad looks a little like this -
ID: 1
Title: Black T-Shirt for Sale
Colour: Black
Size: XL
I've updated the FilterableAttributes to include 'colour' and 'size'.
I pass my search params to my controller like this -
{
"terms": "",
"colour": [],
"location": [],
"params": {
"page": "1"
}
}
If I include 'black' in the Terms - e.g.
{
"terms": "black",
"colour": [],
"location": [],
"params": {
"page": "1"
}
}
I get a search result. But if I pass it in the colour param -
{
"terms": "",
"colour": ["black"],
"location": [],
"params": {
"page": "1"
}
}
I get no search result. My search script looks like this -
$ads = Ad::search($terms)
->when($colour, function ($query, $colour) {
$query->whereIn('colour', $colour); //passing an array to allow multiple colours
})
->where('status', 'active')
->paginate();
I feel like I'm missing something obvious but can't figure out what I'm doing wrong. Would appreciate any help anyone can offer.
Upvotes: 1
Views: 477