Laravel-查询构建器-按列值分组

时间:2018-11-01 00:46:39

标签: php laravel

我有followind表:

Schema::create('rounds', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('color');
    $table->integer('random');
    $table->timestamps();
});

我需要按颜色分组返回它,但是要返回多个组,而不仅仅是每种颜色之一。

我试图表示需要返回数组的方式:

enter image description here

共有三种颜色,分组用红色表示。

例如,我正在使用图像的前6个项目。图片的前6个项目应采用以下格式:

[
  {
    "color": 4,
    "rounds": [
      {
        "random": 12
      }
    ]
  },
  {
    "color": 3,
    "rounds": [
      {
        "random": 32
      }
    ]
  },
  {
    "color": 1,
    "rounds": [
      {
        "random": 56
      },
      {
        "random": 27
      }
    ]
  },
  {
    "color": 4,
    "rounds": [
      {
        "random": 12
      }
    ]
  },
  {
    "color": 3,
    "rounds": [
      {
        "random": 32
      }
    ]
  }
]

2 个答案:

答案 0 :(得分:1)

您需要将表架构更新为:

Schema::create('groups', function (Blueprint $table) { //renamed to groups for better understanding. See each set of randoms as one group having a color (3,4,etc)
    $table->increments('id');
    $table->integer('color');
    $table->timestamps();
});

Schema::create('rounds', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('group_id');
    $table->integer('random');
    $table->timestamps();
});

您必须将其分组存储才能成组获取。

从组到回合创建hasMany关系。

然后,使用以下命令访问数据:

Groups :: orderBy('order')-> with('rounds')-> get();

然后在视图中为您的小组提供帮助。

DB中的示例条目: 组表 groups table sample data 圆桌会议 round table sample data

如果您有顺序记录:

    use Illuminate\Support\Facades\DB;
    public function randoms()
    {
        $allrows = DB::table('rounds')->get();
        $returnarray = [];
        $randoms = [];
        $thiscolor= false;
        foreach ($allrows as $row) {
            if ($row->color != $thiscolor) {
                $thiscolor = $row->color;//save current color reference
                if (isset($randoms['color'])) {//has value
                  $returnarray[] = $randoms;
                } // save previous value to jsonarray
                $randoms=[];//cleat $randoms
                $randoms['color'] = $row->color; // save color
                $randoms['rounds'][]['random'] = $row->random;//save this round
            } else {
                $randoms['rounds'][]['random'] = $row->random;//save round to previous color
            }
        }
        $returnarray[] = $randoms;
        return json_encode($returnarray);
    }

答案 1 :(得分:0)

数据库查询:

DB::table('rounds')
     ->select('*')
     ->groupBy('color')
     ->get();

口才:

Rounds::select('*')
   ->groupBy('color')
   ->get();