radiis
radiis

Reputation: 179

Selecting Items Based on Category

I have two tables 'category' and 'items'. I would like to select five items from each category. I tried my code but it's not working. How can I do it in Laravel?

<?php

$items = DB::table('items')
    ->leftjoin('category', 'category.id', '=', 'items.categoryId')
    ->select('items.id', 'items.name', 'items.categoryId', 'category.categoryName')
    ->groupBy(items . categoryId)
    ->limit(5)
    ->get()

Upvotes: 1

Views: 316

Answers (3)

Samvedna
Samvedna

Reputation: 196

Laravel 5 In Category Model add this relationship

public function items()
  {
    return $this->hasMany(Item::class,'category_id');
  }

In Item Model add this relationship

public function category()
  {
    return $this->belongsTo(Category::class);
  }

Then in controller you can simply write like this

$categories = Category::all();
        return view('tasks.item', [
      'categories' => $categories
    ]);

In view make a foreach loop through category and then call another foreach loop though your items upto 5

@foreach ($categories as $category)
                            <tr>
                                <!-- Task Name -->
                                <td class="table-text">
                                    <div>{{ $category->category_name }}</div>
                                </td>
                                <td>
                                    @foreach($category->items->take(5) as $item)
                                        {{ $item->name }}
                                    @endforeach
                                </td>
                            </tr>
                        @endforeach

Upvotes: 0

Brian
Brian

Reputation: 8616

If you prefere the flaxability of hand-crafted queries, you could do:

// Build and execute query
$sql = "
  SELECT *
  FROM products prod
  JOIN products_categories prodcat ON prodcat.product_id = prod.product_id
  WHERE (product_parent_id = 0 AND product_status = 'published')
  GROUP BY prod.category_id
";
Log::info('getProducts(): ', ['category_id' => $category_id, 'sql' => $sql, 'where' => $where]);
$result = DB::select($sql);

$result will contain an array of objects

Upvotes: 0

jclyons52
jclyons52

Reputation: 316

you could try eager loading items, but I'm not sure how to apply a limit to that. Your best bet might be using multiple queries:

class Category extends Model{
    ...
    public function items(){
        return $this->belongsToMany(App\Item::class);
    }
}
class Item extends Model{
...
}
$categories = Category::all();

$categoriesWithItems = $categories->map(function($category){
    return [
        'category' => $category,
        'items' => $category->items()->take(5)->get(),
    ];
}

Upvotes: 1

Related Questions