【问题标题】:Get group of relationship in laravel在laravel中获取关系组
【发布时间】: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


【解决方案1】:

您可以只做category->get() 或尝试编写原始查询以获取不同的类别,但 category->get 会按照您的意愿完成工作。

【讨论】:

    【解决方案2】:

    您可以像这样获得独特的类别:

    $categories = Items::with('category')->get()->pluck('category')->unique();
    

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 2021-07-28
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多