You need to enable JavaScript to run this app. MySQL查询如何将pickup、dropoff列结果拆分为独立的数组
优惠活动
大模型
产品
解决方案
定价
更多

MySQL查询如何将pickup、dropoff列结果拆分为独立的数组

解决方案

你当前的联表逻辑会生成上车点和下车点的笛卡尔积,同个上下车点会重复出现在多条记录里,只要在查询后用Laravel集合做拆分去重即可,调整后的代码如下:

首先修改查询的select部分补全下车点的id字段,再对查询结果做拆分处理:

// 调整后的查询逻辑,补充dropoff的id字段
$results = DB::table('vehicleschedule')
    ->join("boardingpoints AS pickuppoints", \DB::raw("FIND_IN_SET(pickuppoints.id, vehicleschedule.pickup_points)"), ">", \DB::raw("'0'"))
    ->join("boardingpoints AS dropoff", \DB::raw("FIND_IN_SET(dropoff.id, vehicleschedule.dropoff_points)"), ">", \DB::raw("'0'"))  
    ->select(
        'pickuppoints.title as pickup_title',
        'pickuppoints.id as pickup_id',
        DB::raw("concat(ROUND(( GLength( LineString( pickuppoints.location, GeomFromText('POINT($lat $lng)') ) ) ) * 111), ' KM')  AS distance"),
        'dropoff.title AS dropoff_title',
        'dropoff.id as dropoff_id'
    )
    ->where('vehicleschedule.routeID', '=', $request->input('routeID'))
    ->where('vehicleschedule.vehicleID', '=', $request->input('vehicleID'))
    ->where('vehicleschedule.timeSlot', '=', $request->input('timeSlot'))
    ->where(function ($query) use ($date, $day) {   
        $query->where('vehicleschedule.dayofWeek', '=', $day)
            ->orWhere('vehicleschedule.date', '=', $date);
    })
    ->orderBy('pickuppoints.id')
    ->get();

// 拆分生成pickup数组,按id去重
$pickup = $results->map(function ($item) {
    return [
        'title' => $item->pickup_title,
        'id' => $item->pickup_id,
        'distance' => $item->distance
    ];
})->unique('id')->values()->toArray();

// 拆分生成dropoff数组,按id去重
$dropoff = $results->map(function ($item) {
    return [
        'title' => $item->dropoff_title,
        'id' => $item->dropoff_id
    ];
})->unique('id')->values()->toArray();

// 最终输出的结构
$response = [
    'pickup' => $pickup,
    'dropoff' => $dropoff
];

说明

  • 用unique('id')去除笛卡尔积带来的重复上下车点数据,values()用于重置数组索引,避免返回非连续数字键的结构
  • 补全了dropoff的id查询,满足你输出dropoff数组需要携带id的要求

内容的提问来源于stack exchange,提问作者Muhammad Junaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 17:54:10