2
Well, I found myself in the following situation, I own the entities Vehicle, Vehicle and Optional, where Vehicular is a pivot between the two.
Beauty, there is a vehicle filter on the main page where the user can determine that the resulting vehicles must contain alarm, air-conditioning for example. I tested two methods, add a Count to whereHas:
$query->whereHas('opcionaisThrough', function (Builder $q) use ($filters) {
$q->whereIn('slug', $filters);
}, '>=', count($filters));
And the other place the whereHas inside a loop:
collect($filters)->each(function ($filter) use($query) {
$query->whereHas('opcionaisThrough', function (Builder $q) use($filter) {
$q->where('slug', $filter);
});
});
By the Count method, the result takes about 30-40 seconds. Using the loop, it takes 2-3 seconds, not a considerable time, but the machine in production is having several peaks. Does anyone know a better way to perform this query? I am using the bank Postgres
Relationship as requested:
public function opcionaisThrough()
{
return $this->hasManyThrough(
Opcional::class,
VeiculoOpcional::class,
'veiculo_id',
'id',
'id',
'opcional_id');
}
I tried so and with belongsToMany:
public function opcionaisBelongs()
{
return $this->belongsToMany(Opcional::class, 'veiculos_opcionais');
}
My question was pointed out as duplicate but it has no relation and the user who pointed out I believe did not read my post, the post that was linked to mine concerns HOW to make relationships between model and this was not my doubt. The relationship is not hasMany since I have an intermediate table, hasMany works only for relationships like Customer -> Clientephone.
How relationships are defined in your models?
– Woss
@Andersoncarloswoss edited in the post
– Guilherme Zanini
Relationship is wrong there is a lot to many
– novic
@Virgilionovic is not a duplicate, in fact the post has not even any resemblance to mine, I advise you to give a reread. The relationship is not hasMany since I have an intermediate table, hasMany works only for relationships like Customer -> Clientephone. Another suggestion, I’m new to Stackoverflow but I read for a long time, I always see that when someone tries to contribute a doubt that person points the error and suggests a solution, keeping this in mind, I believe you could improve the quality of your answer.
– Guilherme Zanini
@Guilhermezanini first what I did was only a comment and comments is not an answer. It’s okay to be new, nothing against, it’s good to have new people on the network, but, it’s good that they understand that when we point something out should be observed before saying to me Read ... Laravel is one of my tags that I answer a long time, because I already know, including in the relationship part I already create 3 answers that talk about the subject. The answer is duplicated: https://answall.com/a/168840/54880
– novic