首页 > 解决方案 > Laravel 选择左连接新数组索引中的所有列

问题描述

我在 laravel 查询中有一个问题,在谷歌中搜索并找不到

这是我的查询:

$data = DB::table('event')
        ->where('TU', '!=', null)
        ->where('TM', '!=', 180)
        ->leftJoin('market', 'event.event_id', '=', 'market.event_id')
        ->select([
            'event.event_id as id',
            'TU',
            DB::raw('(TM*60+TS) as elapsed'),
            'markets' => 'market.*'
        ])
        ->orderBy('event.time', 'ASC')
        ->get();

我的结果是这样的:

Collection {#380 ▼
  #items: array:3 [▼
    0 => {#381 ▼
      +"id": 629
      +"TU": 0
      +"elapsed": 1200
      +"default": 1
      +"group_name": "other"
      +"api_updated_at": null
      +"updated_at": "2020-01-31 11:16:11"
    }
    1 => {#382 ▶}
    2 => {#385 ▶}
  ]
}

我希望市场表中的所有列都推入一个索引中

像那样 :

Collection {#380 ▼
  #items: array:3 [▼
    0 => {#381 ▼
      +"id": 629
      +"TU": 0
      +"elapsed": 1200
      +"markets": array:3 [▼
        0 => {#382 ▼
          +"default": 1
          +"group_name": "other"
          +"api_updated_at": null
          +"updated_at": "2020-01-31 11:16:11"
        }
        1 => {#383 ▶}
        2 => {#384 ▶}
      ]
    }
  ]
}

请帮我在 laravel 中编辑查询

标签: phpmysqldatabaselaravel

解决方案


您不能在选择中使用一个字段代替一个表的多个字段。你可以尝试使用

->select([
        'event.event_id as id',
        'TU',
        DB::raw('(TM*60+TS) as elapsed'),
        'market.*'
    ])

或使用with('market')代替leftjoin


推荐阅读