A
A
alex--n2018-11-12 18:04:09
Laravel
alex--n, 2018-11-12 18:04:09

How to use one query builder with different parameters?

Good afternoon. There is a large query builder, which is assembled from several queries. The same query must be used several times, but with different parameters. But I can't find a way to insert different parameters in any way.
An example is very rough:

$query = Client::join('emails', 'emails.client_id', '=', 'clients.id')
->whereIn('email', ['[email protected]', '[email protected]'])
->get();

I need to use the same request, but instead of ['[email protected]', '[email protected]'], I need other mails. I would not want the builder to reassemble every time. I can’t use one request, because it depends on each request whether it will check previous mails or not.
I would like to plan something:
$query = Client::join('emails', 'emails.client_id', '=', 'clients.id')
->whereIn('email', ':arr']);
foreach($cs as $c){
$res = $query->setVars(':arr' => ['[email protected]', '[email protected]'])->get()
}

Perhaps this is a bit far-fetched), but every time I collect a request, I think it's worse

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
miki131, 2018-11-12
@miki131

There is no easy way.
You can try like this

$builder = function($params) {
  return Client::join('emails', 'emails.client_id', '=', 'clients.id')->whereIn('email', $params]);
}

foreach($cs as $c){
  $res = $builder(['[email protected]', '[email protected]'])->get();
}

2
2vtlk, 2018-11-13
@2vtlk

As an option, we make a builder with the main request:
and for reuse, we use it as many times as we like:
with(clone $builder)->where('....', '.....');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question