[英]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實例的事實,這是您的情況。
在您的測試模型中
public function getDateAttribute($value)
{
return Carbon::createFromFormat('Y-m-d H', $value)->format('m');
}
但是這會影響到處的代碼。
public function getFormattedDateAttribute()
{
return Carbon::createFromFormat('Y-m-d H', $this->date)->format('m');
}
$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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.