【问题标题】:getting records by id and querying there relation with 'wherebetween' using Laravel and eloquent通过 id 获取记录并使用 Laravel 和 eloquent 查询与“中间”的关系
【发布时间】:2021-08-17 22:44:40
【问题描述】:

我正在尝试从某个记录器在某个时间跨度之间获取所有测量值。
如果我删除查询的“->wherebetween()”部分并查看结果,那么我将获得该记录仪的所有传感器以及该传感器的所有相关测量值。
但我无法在关系上执行中间关系。

在控制器中查询

public function getChart(Request $request) {
    $sensorCollection = Sensor::where('recorder_id', $request->recorder_id)
        ->with('getMeasurementsRelation')
        ->wherebetween('getMeasurementsRelation', function ($query) use ($request) {
            return $query->wherebetween('timestamp',[$request->start_chart, $request->end_chart]);})
            ->get();
}

传感器模型中的关系

public function getMeasurementsRelation() {
        return $this->hasmany('App\Models\measurement', 'sensor_id', 'id');}

【问题讨论】:

  • 你能贴出 start_chart 和 end_chart 的值格式是什么。也就是 timestamp 是 timestamp 类型
  • @JohnLobo start_chart 和 end_chart 值通过 字段提供,格式为“YYYY-mm-dd”示例 =“2021-05-10”。 “timestamp”列属于“timestamp”类型。
  • 检查我的答案

标签: mysql laravel eloquent laravel-8 eloquent-relationship


【解决方案1】:

您可以通过以下方法使用回调。由于您没有提到开始和结束图表值格式。所以我假设它的 Ymd 格式。如果没有在评论中告诉我,我可以根据您的需要修改我的答案

$sensorCollection = Sensor::where('recorder_id', $request->recorder_id)
        ->with(['getMeasurementsRelation'=>function($query)use($request){
            $startChart=\Carbon\Carbon::createFromFormat('Y-m-d',$request->start_chart)->startOfDay();

            $endChart=\Carbon\Carbon::createFromFormat('Y-m-d',$request->end_chart)->endOfDay();

            $query->wherebetween('timestamp',[$startChart, $endChart]);
        }])

        ->get();

【讨论】:

  • 成功了,谢谢!!!我添加了“->startOfDay ()”和“->endOfDay ()”来将时间格式化为固定点。如果没有这种额外的格式,我会根据您搜索的时间(H:m:s)得到不同的起点和终点。
  • @vennot_be.okay 很高兴您解决了问题
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 2021-05-25
  • 2014-12-10
  • 2021-09-05
相关资源
最近更新 更多