I
I
Ilya Loopashko2022-03-30 13:00:50
Laravel
Ilya Loopashko, 2022-03-30 13:00:50

What is the best way to optimize search code?

I have a code that searches the database according to the given parameters, I know that this one can be optimized, but I can’t figure out how.

I tried Query Builder, but I can't figure it out completely.

public function index(Request $request, Response $response)
    {
        $typeId = $request->get('type');
        $search = $request->get('search');

        if ($typeId && !$search) {

            $element = Element::where('type_id', '=', $typeId)
                ->where('title', 'like', '%' . $search . '%')
                ->get();

            $response->setMessage('Данные успешно загрузил 1');

        } elseif ($typeId && $search) {

            $element = Element::where('type_id', '=', $typeId)
                ->where('title', 'like', '%' . $search . '%')
                ->get();

            $response->setMessage('Данные успешно загрузил 2');

        } elseif (!$typeId || $search) {

            $element = Element::where('title', 'like', '%' . $search . '%')->get();
            $response->setMessage('Данные успешно загрузил 3');

        } elseif ($typeId == null && $search == null){

            $element = Element::get();
            $response->setMessage('Данные успешно загрузил 4');
        }

        $response->setStatus('OK');
        $response->setData(['Element' => $element->load('elementtype')]);

        return $response->asJson();
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2022-03-30
@deadloop

something like this:

$builder = Element::query();
$loadType = 0;
if ($typeId) {
$builder->where('type_id', $typeId);
$loadType |= 1;
}
if($search) {
$builder->where('title', 'like', "%$search%");
$loadType |= 2;
}

$element = $builder->get();
$response->setMessage("Данные успешно загрузил $loadType");

$response->setStatus('OK');
$response->setData(['Element' => $element->load('elementtype')]);
        return $response->asJson();

T
TheAndrey7, 2022-03-30
@TheAndrey7

The first two blocks "Data successfully loaded 1/2" are the same. Remove duplicate and optimize if.
Also, indexes should be written in the database table to speed up the search for records.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question