如何使用groupby从公共列下的sql/mysql获取嵌套数组,而不使用foreach来构造数据?

aoyhnmkz  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(231)

比如说table tracker 包含此 columns(id,section,user_id,message) 另一个是 user 包含用户数据和 user_id 是表中的外键 tracker 所以我用 join 从…得到名字 user 我用的是 laravel .
React就像this:-

{'id'=1,'name'='pavan','section'='marketing','message'='something'}

所需的结构是下的嵌套数组 user_id 就像this:-

{
//user_id 1:
  [name,section,message],
 2:
  [name,section,message]
}

我怎么用这个 MySQL 询问?
//用户模型

<?php

 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

 class CreateUsersTable extends Migration
 {
 /**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
 {
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
 }

 /**
 * Reverse the migrations.
 *
 * @return void
 */
 public function down()
 {
    Schema::dropIfExists('users');
 }
 }

//跟踪器模型

public function up()
{
    Schema::create('trackers', function (Blueprint $table) {
        $table->increments('id');
        $table->enum('section',['Marketing','Sales','Customer','Trainer','Operations']);
        $table->string('subject')->nullable();
        $table->longText('content');
        $table->enum('status',['processing','resolved']);
        $table->date('date');
        $table->unsignedInteger('user_id');
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users');

    });
}

//跟踪器模型中的数据获取方法

public function getdata(){
        return \DB::table('trackers')
        ->join('users','users.id','=','trackers.user_id')
        ->select('trackers.user_id','users.name',
          'trackers.created_at','trackers.id','date',
          'trackers.status','trackers.section','trackers.content')
          ->orderBy('created_at','DESC')->get();
        }

//查询

$dat=new Tracker;
  $data=$dat->getdata()->where('date',Carbon::today()->
  toDateString())->where('status','processing');
ecbunoof

ecbunoof1#

$dat=new Tracker;
  $data=$dat->getdata()->where('date',Carbon::today()->
  toDateString())->where('status','processing')->get();
``` `get()` 将在获取您可以使用的集合后返回集合
你可以用

$dat->groupBy('user_id');

这将按预期返回数据。
你可以得到更多关于 `collection->groupby()` https://laravel.com/docs/5.6/collections#method-groupby公司

相关问题