繁体   English   中英

我可以在 Laravel5 上获取 pluck(lists) 的自定义日期格式吗?

[英]Can I get custom date format for pluck(lists) on Laravel5?

我的数据库记录是这样的。

tests table
id date
1 2016-07-01
2 2016-07-31
3 2016-08-01
4 2016-08-15
5 2016-08-31
6 2016-09-01

我想按月选择记录。 现在我的代码是这样的。

Controller

$months = \App\Test::where('date', '<=', 'now()')
                          ->orderBy('date', 'desc')
                          ->pluck('date', 'date');

看法

{{ Form::select('month', $months, old('month'), ['id' => 'month']) }}

( that generate this. )

<select id="month" name="month">
    <option value="2016-07-01">2016-07-01</option>
    <option value="2016-07-31">2016-07-31</option>
    <option value="2016-08-01">2016-08-01</option>
    <option value="2016-08-15">2016-08-15</option>
</select>

但我想要这个。

$months = \App\Test::where('date', '<=', 'now()')
                          ->orderBy('date', 'desc')
                          // ->format('m').
                          ->pluck('date', 'date');

{{ Form::select('month', $months, old('month'), ['id' => 'month']) }}

( I wanna generate this )

<select id="month" name="month">
    <option value="7">7</option>
    <option value="8">8</option>
</select>

我想使用 pluck 的格式,但遗憾的是不能这样做任何解决办法?

你可以通过三种方式做到这一点。 所有这些解决方案都取决于date属性不是Carbon实例的事实,这是您的情况。

  1. date属性的访问器,用于返回您希望的格式:

在您的测试模型中

test.php的

public function getDateAttribute($value)
{
    return Carbon::createFromFormat('Y-m-d H', $value)->format('m');
}

但是这会影响到处的代码。

  1. 第二种方法是创建自定义属性。
public function getFormattedDateAttribute()
{
    return Carbon::createFromFormat('Y-m-d H', $this->date)->format('m');
}
  1. 第三种方法是编辑集合本身。
$months = \App\Test::where('date', '<=', 'now()')
                                      ->orderBy('date', 'desc')
                                      ->pluck('date');

$months->each(function($month){
            return Carbon::createFromFormat('Y-m-d H', $month)->format('m');
        });
$months = \App\Test::select(DB::raw('to_char(date, \'MM\')'))
                      ->where('date', '<=', 'now()')
                      ->orderBy('date', 'desc')
                      ->pluck('date', 'date');

这将为您提供一个月份列表。

更多信息

谢谢大家,我昨天放弃了从DB获得的月份,但是今天!! 我得到了这个代码XD的正确答案。 注意,此代码仅适用于Postgresql,其中...... now()也适用。 这是postgres代码。 Mysql或sqlite必须更改DB raw和代码ya。

$months = \App\Test::select(\DB::raw('DATE_PART(\'MONTH\', date) AS MONTH'))
                        ->where('date', '<=', 'now()')
                        ->orderBy('date', 'desc')
                        ->pluck('month', 'month');

您可以像这样同时摘下和取出 Carbon date getter:

->pluck('date.month');

吸气剂来源https://carbon.nesbot.com/docs/#api-getters

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM