Skip to content
This repository has been archived by the owner on Jan 9, 2024. It is now read-only.

Indexing & Searching Relationships #96

Open
chris-mackie opened this issue Feb 17, 2020 · 2 comments
Open

Indexing & Searching Relationships #96

chris-mackie opened this issue Feb 17, 2020 · 2 comments

Comments

@chris-mackie
Copy link

I am trying to include categories in my search but not getting any results.

I'm searching the main table "Posts" where there is a hasMany relationship to "Categories" and this has a hasOne relationship to "CategoryList" which has the column "name". This name column is the one that I want to include in the index when updating Posts so posts are searchable via the category name.

Is this possible?

@wlius-support3
Copy link

I think the best workaround is to create a MySQL View.
Brent from Spatie has a good article on it.

You can then reference the "MySQL View" model (which is still a regular eloquent model, it just points to a view instead of a table), and now you can search across relationships because the view can be built to join the relationships.

@sawtell
Copy link

sawtell commented Nov 23, 2020

Thanks @wlius-support3 for the idea to use a View.

This may help others:
I needed to perform the search on the "main" model (and return it as the result) but obviously use the View model for the actual search query.

I overrode the search() method on the main model so that the query is performed on the search View.

MainModel.php

public static function search($query = '', $callback = null) {
    return app(Builder::class, [
        'model' => new MainModelSeachView(), // Just this changed from the parent implementation.
        'query' => $query,
        'callback' => $callback,
        'softDelete'=> static::usesSoftDelete() && config('scout.soft_delete', false),
    ]);
}

Then in the View model I overrode newFromBuilder() in order to return the result as the main model.

MainModelSearchView.php

public function newFromBuilder($attributes = [], $connection = NULL) {
    return MainModel::find($attributes->id); // Ensure the ID is available in the View table
}

This way I can perform a search like MainModel::search('query') but the View is queried and I still get the result as a collection of MainModels.

Would love to know if there's a better way to do this.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants