在选择查询MYSQL中选择

时间:2017-12-03 05:31:21

标签: php mysql laravel

你好!我有一个需要输出屏幕数据的查询 每个屏幕都有4个展位。我需要一个查询结果(因为我只有一个屏幕)并且有4个展位(因为我分配了4个展位)

这是我的疑问:

$result = DB::select("
    SELECT
        `A`.`scr_name`,
        `A`.`mission_id`,
        `B`.`booth_id`,
        `E`.`name`
    FROM `tbl_screen` `A`
    LEFT JOIN
        `tbl_screen_booths` `B`
    ON `B`.`screen_id` = `A`.`id`
    LEFT JOIN
        `tbl_service_booths` `C`
    ON `B`.`booth_id` = `C`.`id`
    LEFT JOIN
        `tbl_missions_services` `D`
    ON `C`.`mission_services_id` = `D`.`id`
    LEFT JOIN
        `tbl_services` `E`
    ON `D`.`service_id` = `E`.`id`
    WHERE `A`.`mission_id` = $mission_id
    GROUP BY
        `B`.`booth_id`;
");

return $result;   

我想要这样的东西:

"scr_name": "Test Screen",
"mission_id": 2,
"name": "booth1", //index[0]
"name": "booth2", //index[1]
"name": "booth3", //index[2]
"name": "booth4" //index[4]

我的查询返回如下内容:

[
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 7,
"name": "booth1"
},
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 9,
"name": "booth2"
},
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 10,
"name": "booth3"
},
{
"scr_name": "Test Screen",
"mission_id": 2,
"booth_id": 11,
"name": "booth4"
}
]

1 个答案:

答案 0 :(得分:1)

结果还可以..只需要一点迭代就可以得到值..

$data['scr_name'] = $result[0]->scr_name;
$data['mission_id'] = $result[0]-> mission_id;

foreach($result as $index => $item) {
     $data['name'.($index+1)] => $item->name;
}

结果:

"scr_name": "Test Screen",
"mission_id": 2,
"name1": "booth1", //index[0]
"name2": "booth2", //index[1]
"name3": "booth3", //index[2]
"name4": "booth4" //index[4]

数组键不能具有相同的键名