N
N
NikSIk312021-06-22 21:29:38
Laravel
NikSIk31, 2021-06-22 21:29:38

Laravel merge search results?

I have 2 tables with DIFFERENT number of columns. And there is a trait that searches for certain columns in the table (in this case, these columns are present in two tables).

To search in the same table I call:
Studio::search($request->s)->get();

How can I merge search results from two tables with pagination?

Trait code just in case:

<?php

namespace App\Models;

trait FullTextSearch
{
    /**
     * Replaces spaces with full text search wildcards
     *
     * @param string $term
     * @return string
     */
    protected function fullTextWildcards($term)
    {
        // removing symbols used by MySQL
        $reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~'];
        $term = str_replace($reservedSymbols, '', $term);

        $words = explode(' ', $term);

        foreach($words as $key => $word) {
            /*
             * applying + operator (required word) only big words
             * because smaller ones are not indexed by mysql
             */
            if(strlen($word) >= 3) {
                $words[$key] = '+' . $word . '*';
            }
        }

        $searchTerm = implode( ' ', $words);

        return $searchTerm;
    }

    /**
     * Scope a query that matches a full text search of term.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $term
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $term)
    {
        $columns = implode(',',$this->searchable);

        $query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)" , $this->fullTextWildcards($term));

        return $query;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin, 2021-06-24
@derwin

there are several problems. Either you use sql with offset/limit for pagination with loading only a specific page, or you upload data to an array and paginate all data from tables in an array in RAM.
If you have fat on the RAM, or little data in the tables, then there are no problems.
If there is a lot of data, nothing will work for you, you need to concatenate the data into one final structure. And work at the SQL level

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question