hhsadiq
hhsadiq

Reputation: 2953

Calling searchable() on Query Builder based result throws errors

How to use searcable() method on results returned by query builder? Suppose there are five tables:

  1. products
  2. vendors
  3. categories
  4. vendor_products (pivot table for Products and Vendors)
  5. product_categories (pivot table for Products and Categories)

Is there a way to use searchable on the following query:

   return \DB::table("products")
      ->join('vendor_products', function ($join) {
          $join->on('products.id', '=', 'vendor_products.product_id')
               ->MANY_OTHER_WHERE_CONDITIONS
      })
      ->join('categories', function ($join) {
          $join->on('category_id', '=', 'categories.id');
      })
      ->MANY_OTHER_CONDITIONS
      ->searchable()

But Laravel Scout return error:

Call to undefined method Illuminate\Database\Query\Builder::searchable()  

Is there a way to upload the results of above query? I have added searcable trait on vendors, categories, and products models.

It looks like Scout only work when we have Eloquent relationship returned from the query and don't work on query builder.

Upvotes: 0

Views: 767

Answers (2)

hhsadiq
hhsadiq

Reputation: 2953

Problem resolved, all credit goes to @kfirba. Copying his response from his blog

The searchable() method is only available for Eloquent’s query builder. Try converting your query above to use Eloquent. Change the DB::table(‘products’)->join... to Products::join...

You may need to change the “toSearchableArray()” method implementation to include your new fields that are not part of the Product model (vendor_quantity, vendor_price, etc.)

Upvotes: 1

Acording to Laravel Documentation

Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models.

Query builder doesn't have this functionality.

Instead, a non so fancy solution you could implement is to compare every column using WHERE LIKE. This supposes a more slowly functionality than Laravel Scope but can do the trick if you dont want to use Eloquent.

My Recomendation is to use Eloquent. Is a faster and easier way to work with databases while using laravel

Upvotes: 1

Related Questions