mysql - 从多个表中选择数据 - 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();
如果存在给定日期的位置记录,则预期输出是具有给定容量的车辆及其在给定日期的位置的列表。
解决方案
使用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();
推荐阅读
- php - 循环遍历一个数组(+100 个值)
- javascript - 获取下拉框更改值
(来自 MySQL)
- python - 我需要帮助了解线程利用率
- api-gateway - 通过 Datapower 网关脚本获取无效 XML 的响应负载
- c# - 如何将对象传递给包含 .NetCore 中的 html 字符串的控制器
- reactjs - 尽管有文件加载器(url-loader),但图像没有在使用 Webpack 的 React 应用程序中加载
- cuda - 为什么在这里使用 ceil 以及它的用途是什么
- selenium - 是否可以使用 Selenium 保存浏览器控制台的命令输出?
- python - 如何从包含所有链接列表的文本文件中下载 1 次运行?
- dockerfile - 在我的 Docker 文件中包含其他 Docker 文件