【发布时间】:2018-09-20 09:35:29
【问题描述】:
我正在使用 laravel 4.2,并且我有一个模型 Items,该模型项属于模型 Category,模型 Category 有一些文本和一个用于搜索漂亮 url 的 slug。
商品型号:
class Item extends Eloquent{
public function category()
{
return $this->belongsTo('Category','cat_id');
}
}
类别型号:
class Category extends Eloquent{
}
如果我这样做 Items::with('category')->get() 它会检索到这个:
//items
[
{
"id": 26,
"cat_id": 14,
"category": {
"id": 14,
"slug": 'unique-text',
"description": 'text',
}
},
{
"id": 25,
"cat_id": 13,
"category": {
"id": 13,
"slug": "unique-text2",
"description": "text2",
},
{
"id": 25,
"cat_id": 13,
"category": {
"id": 13,
"slug": "unique-text2",
"description": "text2",
},
]
问题
如何在不必访问每个item 的情况下从关系中检索categories,以及如何仅检索那些不重复的categories。
例如,在上面显示的数据中,有2个项目具有相同的category id = 13
我只想在 group by 中显示 Categories: text / text2。
已编辑
Item 可能会被过滤,所以我需要基于Item 查询结果的类别,所以如果我这样做Item::where('price','>','20')-with('category')->get() 我需要对这些项目的类别进行分组,我不需要所有项目。
【问题讨论】:
-
你可以做
category->get()或尝试做原始查询
标签: laravel relationship laravel-eloquent