K
K
Konstantin2018-11-20 02:21:42
Laravel
Konstantin, 2018-11-20 02:21:42

How does whereHas work in Laravel?

How does whereHas work in Laravel in this example:

$orders = OrderModel::whereHas('User', function ($query) {
            if ($request->has('term')) {
                $query->where('LastName', 'like', $request->term);
            }
        });

How many queries will Laravel build if the condition is true, $query->where()and what query will it build otherwise?
And is it possible to dynamically create a query based on input data, something like this:
$query = "SELECT * FROM TABLE";

if ($request->data) {
  $query+= " lEFT JOIN TABLE 2 ON..."
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Mashletov, 2018-11-20
@Junart1

How does whereHas work in Laravel?

Just whereHas:
If we add more with:
Great article

A
Anton [RuleZzz] Shipulin, 2018-11-21
@rul22rus

Instead of ->get() or ->first() you can call ->toSql() it will show the current query template

E
Eugene Wolf, 2018-11-20
@Wolfnsex

How many queries will Laravel build if the $query->where() condition is met, and what query will it build otherwise?
This can be easily found out from the database logs or the debug panel for Laravel.
And is it possible to dynamically create a query based on input data, something like this:
Maybe. And what prevents you from building such requests?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question