Ok, I have 2 tables;
PROFORMA
- EQUIPOS
(a third one that is a project, but that relationship is not the problem)
Well in programming what I need to do is something like this:
What I had to do is already solved, the issue is that I would like this to be done in the controller and not in the blade.
Well now the issue is that, I have made a condition proformas.blade
where it verifies that fk_equipos_proforma
it is equal to the one id
in the proforma so that when I do @foreach
it it shows me the equipment corresponding to that proforma, because they are n
proformas that are shown no 1.
and I want to see if someone can help me with the condition that I have in the blade, I can do it in the controller:
Blade condition:
<tbody class="t-equipos-body">
@foreach ($filas as $item2)
<tr>
@if ($item->id_proforma == $item2->fk_equipos_proforma)
<td>{{$item2->descripcion}}</td>
<td>{{$item2->cantidad}}</td>
<td>$ {{$item2->precio_unidad}}</td>
<td>$ {{$item2->total_fila}}</td>
@endif
</tr>
@endforeach
</tbody>
So my question is how to make the query in the controller that can make me that same condition.
@if ($item->id_proforma == $item2->fk_equipos_proforma)
$item (PROFORMA)
$item2 (EQUIPOS)
For now I only have these queries:
$proformas = DB::table('proforma')->where('fk_proforma_proy', $datos)->get();
$filas = DB::table('equipos')->where('fk_equipos_proy',$datos)->get();
For your scenario we require 2 models, which are:
The syntax is simple:
Each of these models will have a declared relationship that links them to their counterpart model, as follows:
The Proforma model has many teams so use the method
hasMany()
like this:On the other hand Team belongs to... and then use the method
belongsTo()
like this:Now we build the query where:
eager loading
passing as argument the name of the relationid
to only obtain the equipment related to itThus:
Where
$idProforma
is the variable that stores the id of the proforma that you want to use to get its related equipment.Finally to be able to iterate them we do the following in the view
The previous query should be returning at the level of the first foreach the values of the properties of the proforma model and within the second foreach the values of the properties of the Team model.
On the other hand, if you want all the proformas with their associated equipment, then just replace the use of
findOrFail()
with that ofget()
, the rest should remain the same:Clarifications:
columna_id
so in the methodhasMany()
as the second argument you must pass the name of said foreign key as a string.References