I think you can use Eager Loading (Eager Load Constraints
) to reduce the n+ query problem
using with
method:
$metalsWithFixes = Metal::with(array('fixes' => function($q){
$q->where('currency_id', Session::get('currency'));
}))->get();
Update: You can use the relationship as $metalsWithFixes->first()->fixes
and can select fields from fix
tablw but the relation key (metal_id
) must be present in the select array
:
$metalsWithFixes = Metal::with(array('fixes' => function($q){
$q->where('currency_id', Session::get('currency'))->select(array('metal_id', 'am'));
}))->get();
You can use a loop
in your view (blade)
as:
@foreach($metalsWithFixes as $metal)
{{ $metal->fieldName }}
@foreach($metalWithFix->fixes as $fix)
{{ $fix->am }}
@endforeach;
@endforeach
Since, it's a one-to-many
relationship so the $metal->fixes
will return more than one fix
or one (if there is only one) but as an array
.