SQL Laravel GroupBy and show all records

时间:2017-05-16 09:39:27

标签: php mysql sql laravel

I have the following structure for my database table:

staff_id column_id data

I'm trying to find a way so that I can view all the column_id and data fields for a given staff_id

For example there could be 6 records with a staff_id of 2 and 33 records with a staff_id of 1.

Now I need to get this so that I have an array which I can loop through which will provide me all the data.

So in PHP something like:

foreach($staffs as $staff) {
    foreach($staff->datas as $data) {
        echo $data->column_id . " - " . $data->data . "<br />";
    }
    echo "<hr />";
}

I've looked at GroupBy but that seems to only return one result when grouped.

I'm using Laravel.

3 个答案:

答案 0 :(得分:3)

员工模特

  public function datas(){
      return $this->hasMany(DataTable::class,'staff_id');
   }

现在您可以使用:

$staffs=Staff::with('datas')->get(); // get data with relltionships

foreach($staffs as $staff) {
    foreach($staff->datas as $data) {
        echo $data->column_id . " - " . $data->data . "<br />";
    }
    echo "<hr />";
}

答案 1 :(得分:0)

使用Illuminate\Support\Collection您可以:

$staffs->groupBy(function ($staff) {
    return $staff->staff_id;
});

答案 2 :(得分:0)

假设我有列表,这里是结构

lists
-------

id | staff_id | column_id (int) | data(string) | 

现在我创建ListController并编写返回staff_id特定数据的方法getstaff()

 public function getstaff($id){
     $staffs = List::where('staff_id','=',$id)->get();
     return $staffs;
   }

现在你可以在刀片中显示

@foreach($staffs as $staff)
    <li>{{$staff->column_id}}</li>
    <li>{{$staff->data}}</li>
   @endforeach