首页 > 解决方案 > 从多个表中选择数据 - laravel

问题描述

我有两张表,一张记录车辆详细信息,另一张记录特定日期车辆的位置。

车辆表 位置表

我想获取在给定日期具有特定容量及其位置的车辆的编号和类型。

例:2019-08-07所有9t车辆及其位置

我曾尝试使用连接和子查询来获得确切的输出,但它们都没有奏效。

这是我当前的代码,它为同一辆车输出多条记录。

$vehicles = DB::table('vehicles as v')
            ->leftJoin('current_location as l', 'v.vehicle_id', '=', 'l.vehicle_id')
            ->leftJoin('locations as k', 'l.location_id', '=', 'k.location_id')
            ->select('v.vehicle_id as vehicle_id','v.type as type','v.capacity as capacity', 'k.location as location')
            ->where('v.capacity', $request->capacity)

            // ->where(function($query) use ($request)
            // {
            //     $query->where('l.date', $request->date)
            //           ->orWhere('l.date', null)
            // })

            ->get();

输出

如果存在给定日期的位置记录,则预期输出是具有给定容量的车辆及其在给定日期的位置的列表。

标签: mysqllaravelselecteloquentleft-join

解决方案


使用Eloquent可以轻松实现。

Vehicle.php

public function currentLocations()
{
   return $this->hasMany(CurrentLocation::class, 'vehicle_id', 'vehicle_id');
}

在模型中CurrentLocation.php

public function location()
{
   return $this->belongsTo(Location::class, 'location_id', 'location_id');
}


Vehicle::with(['currentLocations' => function($q) {
    $q->where('date', request('date'));
}, 'currentLocations.location'])
->where('capacity', request('capacity'))
->get();


推荐阅读