【问题标题】:Laravel 5.2 trouble with SQL query in eloquentLaravel 5.2 在 eloquent 中遇到 SQL 查询问题
【发布时间】:2017-01-20 19:05:26
【问题描述】:

我在 Laravel 5.2 中的 eloquent 遇到问题

我想要实现的是(希望)一个满足这些步骤的查询:

  1. updated_at >= value1
  2. updated_at
  3. 事件 = value3
  4. groupBy = value4
  5. 计算每个“组”的条目(每个按组分组)

输出:每组的最新 updated_at (max(updated_at)) 和每组的计数值

到目前为止我所拥有的是:

表“日志”概述:

---------------------------
| id         | increment    |
-----------------------------
| key        | varchar(255) |
-----------------------------
| video_id   | varchar(255) |
-----------------------------
| event      | varchar(255) |
-----------------------------
| created_at | timestamp    |
-----------------------------
| updated_at | timestamp    |
-----------------------------

在 Laravel 中查询:

$showed = self::where('updated_at','>=',$value1)->where('updated_at','<=',$value2)->where('event',$value3)->groupBy($avlue4)->get();

我缺少的是第 5 步和结果输出。而且我不知道如何将其包含在 Laravel 雄辩中。

问题:有人对如何实现此查询有具体的想法吗?如果不可能,应该采取什么步骤?

【问题讨论】:

  • 请分享表定义和所需的输出。这不是 Laravel 特定的,您首先需要对正在查询的表进行适当的 SQL 查询。
  • 您需要为要返回的聚合列“count”传递一个表达式

标签: php mysql laravel-5.2


【解决方案1】:

你可以像这样传递一个条件数组:

$showed = DB::table('tableNameHere')->where([
    ['updated_at', '>=', $month_start],
    ['updated_at', '<=', $month_end],
    ['event', '=', 'showed'],
])->groupBy('id')->get();

要计算条目,您可以这样尝试:

$results = $showed->count();

无法测试代码。让我知道这是否有效。

【讨论】:

  • 对结果的计数为我提供了所有条目的总数。理想情况下,我希望每个“排序组”(每个“id”组)都被计算在内,并且每个组的最新 updated_at 值与该计数值一起返回。
【解决方案2】:

如果有人在构建这种 eloquent 时也遇到麻烦:我的解决方案是按 ID 对查询进行分组,因此 Array 中的条目将类似于:

[0] => [Object, Object],
[1] => [Object]

我的查询:

$temp = self::where('updated_at','>=',$month_start)
        ->where('updated_at','<=',$month_end)
        ->where('event','completed')
        ->orWhere('event', 'showed')->get();
    $result = $temp->groupBy('id')->toArray();;

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多