如何从2个表创建嵌套的json对象查询?

时间:2019-09-13 20:06:38

标签: php json laravel

我需要做出一个json看起来像这样的结果

{"data":[
    {"id":2,
    "name":"miles",
    "email":"sb-o8c47x137031@personal.example.com",
    "details":{
        "id":11,
        "product_id":"product-003","purchase_rebate":2,
        "purchase_rebate_date":"2019-09-10 23:07:33",
        "survey_ans_rebate":2,"survey_ans_rebate_date":"2019-09-10 23:07:33",
        "created_at":"2019-09-10 23:07:33","updated_at":"2019-09-10 23:07:33"
        },
    },
    {"id":3,
    "name":"Jayson",
    "email":"sb-rv9me150874@personal.example.com",
    "details":{
        "id":13,
        "product_id":"product-010",
        "purchase_rebate":2,
        "purchase_rebate_date":"2019-09-11 04:26:24",
        "survey_ans_rebate":2,
        "survey_ans_rebate_date":"2019-09-11 04:26:24",
        "created_at":"2019-09-11 04:26:24",
        "updated_at":"2019-09-11 04:26:24"}
    }
    ]
}

这是我的服务器端PHP脚本

$get_merchant_users = DB::table('merchant_users as a')
            ->leftjoin('user_transactions as b', 'b.email','=','a.email') 
            ->select('a.id','a.name',DB::raw('SUM(b.purchase_rebate) + SUM(b.survey_ans_rebate) as total'),'a.email')
            ->groupBy('a.id','a.name','a.email')         
            ->get();
            $details = DB::table('user_transactions')
            ->select('*')
            ->get();
            $data = array('data'=> $get_merchant_users,'details'=> $details);
            return $data;

1 个答案:

答案 0 :(得分:0)

快速的肮脏解决方案(可能的性能问题)

$get_merchant_users = DB::table('merchant_users as a')
    ->select('a.id', 'a.name', 'a.email')
    ->get();

foreach ($get_merchant_users as $merchant_user) {
    $details = DB::table('user_transactions')
        ->select('*')
        ->where('email', '=', $merchant_user->email)
        ->get();

    $data[] = ["id" => $merchant_user->id,
        "name" => $merchant_user->name,
        "email" => $merchant_user->email,
        "details" => $details->toArray()];
}

我不知道您的表结构,但是我认为不需要groupBy('a.id','a.name','a.email'),最好使用主键联接表。