1
I have 3 tables (clientes,seguradoras e clientes_seguradoras)
that relate through 2 Models (Cliente e Seguradora)
in Laravel
Each customer can have several insurers, and for each insurer he can add his price.
Tables follow the following structure:
clientes:
- nome,
- sobrenome
.....
seguradoras:
- nome,
- imagem
.....
clientes_seguradoras:
- cliente_id,
- seguradora_id,
- preco <-- valor que quero somar
.....
The relationship between client and insurer is made as follows in the model Cliente
:
public function seguradoras()
{
return $this->belongsToMany('App\Models\Seguradora', 'clientes_seguradoras', 'cliente_id', 'seguradora_id')
->withPivot(['preco']);
}
Use the model Cliente
with insurers as follows Controller
responsible for carrying out searches:
$clientes = Cliente::with(['seguradoras'])
// .... algumas condições where() em cima do cliente
->paginate(50);
But I can only do the sum by doing a "in hand" foreach inside the view itself with the data from paginate(50)
, only that the paginate
is limited to the results displayed on the page and not to the total result of the search (model query), and return all the results at once and make a foreach is not efficient and consumes a lot of memory, as there are thousands
How can I do a query to sum the total price of the pivot table by keeping any "Where" I do on top of the client model?
Do you want to get out which result? (for example line) would be better ai a Join with groupby ...
– novic
I wanted the float of the sum, I solved with a Join and group by on top of the Customer model, but I wanted to know if there is any more "elegant" solution with Eloquent
– Thiago
how did you do? one can create Scope etc ... but, face the Builder is equal and a pull of the Eloquent
– novic