mysql - 根据类别选择项目

标签 mysql laravel laravel-5 laravel-query-builder

我有两个表 '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()

最佳答案

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

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(),
    ];
}

关于mysql - 根据类别选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35055998/

相关文章:

php - 如何在 Laravel Voyager 中创建自定义 Controller

php - 如何在 yii 1.13 中将所选爱好的 ID 保存在数据库中

mysql部分索引、反向索引

php - laravel 查询构建器中 select 的内部查询?

php - Laravel 5 Auth::attempt() 总是返回 false

php - 使用 Redis 的速率限制 laravel 队列

php - Laravel Nova - 如何从 HasMany 字段中隐藏 'Create' 按钮?

mysql - 如何在 WHERE 子句中使用日期插入记录?

mysql - 将不同的计数值分组在一行中

php - 从一张表返回结果