Chris0089
Chris0089

Reputation: 39

Query inside foreach Laravel 4 Controller/view

Well, in my view I've a foreach and I display the id of a product with {{$look->item1_id}} but i need the name, so I need to look to another table to look the name, but how?

I have a little store where some items create different "looks".

My db looks like this:

items table:
id/item_name/other_fields

looks table:
id/look_name/item1_id/item2_id/item3_id

my controller looks like:

$looks=Look::where('gender', '=', "girls")->get(); 
return View::make('store')->with('looks', $looks)

So in my view:

   @foreach ($looks as $looks)
        Id: {{$looks->item1_id}} 
        Name: ??
   @endforeach

My model:

class Look extends Eloquent
{
    protected $table='looks';
}
class Item extends Eloquent
{
    protected $table='items';

}

I know with Eloquent Relationships could be done, but I cannot change the db.

Thanks

Upvotes: 1

Views: 910

Answers (1)

PaulusDixit
PaulusDixit

Reputation: 26

You should use a relation, but as you want to, you could just run a query and get the name of the item.

DB::table('items')->where('id', $looks->item1_id)->pluck('item_name')

Keep in mind that with every loop a query will be performed. If you'll expect a lot of queries you might want to use this code:

// Outside the loop
$items = DB::table('items')->where('id', $looks->item1_id)->list('item_name', 'id')

// Inside the loop
$items[$looks->item1_id]

Good luck!

Upvotes: 1

Related Questions