【问题标题】:Laravel 5.4 - Get one data from each duplicate data rowLaravel 5.4 - 从每个重复数据行中获取一个数据
【发布时间】:2018-02-12 15:24:21
【问题描述】:

我想选择选项来显示从表的 created_at 列中获取的月份

// item_ins
+----+--------+---------------------+
| id |  item  |     created_at      |
+----+--------+---------------------+
|  1 | item 1 | 2017-12-11 10:37:52 |
|  2 | item 2 | 2017-12-11 10:38:17 |
|  3 | item 3 | 2018-01-12 01:28:43 |
|  4 | item 4 | 2018-01-12 01:30:14 |
|  5 | item 5 | 2018-02-12 01:30:05 |
|  6 | item 6 | 2018-02-12 01:30:42 |
+----+--------+---------------------+

表格里有12月、1月和2月各两个月,我想每个月拿一个,我试试这样

$months= ItemIn::distinct('created_at')->pluck('created_at');

但我每个月的两个月还是一样的,因为时间不一样,如下

我仍然对如何获得一个月感到困惑,因为通过上述方式我也获得了年和日

[
    {
        "date": "2017-12-11 10:37:52.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    {
        "date": "2017-12-11 10:38:17.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    {
        "date": "2018-01-12 01:28:43.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    {
        "date": "2018-01-12 01:29:14.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    {
        "date": "2018-02-12 01:30:05.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    {
        "date": "2018-02-12 01:30:22.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
]

【问题讨论】:

  • 使用日期格式选择 created_at,以便省略时间部分。

标签: php laravel sqlite laravel-5 laravel-5.4


【解决方案1】:

如果时间的存在不是问题,您可以在使用选择查询本身时处理此问题,如果您正在选择,则使用子字符串。

select id, item, SUBSTRING(created_at, 1, 11) as created_at
from test
group by created_at;

【讨论】:

    【解决方案2】:

    将 CAST 与原始查询一起使用以获得您想要的结果,

    $data = \DB::table('item_ins')
            ->select(\DB::raw('CAST(created_at as date) as created_at'))
            ->distinct('created_at')->get();
    

    您可以在此处查看文档https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html

    希望你能理解。

    【讨论】:

      【解决方案3】:

      在视图中使用 Carbon

      对其进行格式化
      {{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
      

      或在模型中使用accessors 重新格式化日期字段

      public function getCreatedAtAttribute($value) {
           return \Carbon\Carbon::parse($value)->format('m');
      }
      

      然后$model->created_at 将采用所需的格式

      【讨论】:

        【解决方案4】:

        使用groupBy():

        $months = ItemIn::groupBy(DB::raw('MONTH(created_at)'))->selectRaw('DATE_FORMAT(created_at, "%M") as month')->get();
        

        【讨论】:

          猜你喜欢
          • 2020-03-19
          • 2017-08-13
          • 2017-12-09
          • 2017-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-14
          • 1970-01-01
          相关资源
          最近更新 更多