1

我有两张桌子'category''items'. 我想从每个类别中选择五个项目。我尝试了我的代码,但它不起作用。我怎样才能在 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()
4

3 回答 3

1

您可以尝试急切加载项目,但我不确定如何对其应用限制。您最好的选择可能是使用多个查询:

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(),
    ];
}
于 2016-01-28T08:50:16.873 回答
0

如果您更喜欢手工查询的 flaxability,您可以这样做:

// 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将包含一个对象数组

于 2016-01-28T09:00:08.280 回答
0

Laravel 5 在类别模型中添加此关系

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

在项目模型中添加此关系

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

然后在控制器中你可以简单地这样写

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

在视图中通过类别进行 foreach 循环,然后通过最多 5 个项目调用另一个 foreach 循环

@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
于 2016-01-28T09:15:02.997 回答