gpt4 book ai didi

mysql - 根据类别选择项目

转载 作者:行者123 更新时间:2023-11-28 23:38:36 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com