2016-03-10 49 views
1

如何將laravel中的日期格式從「2016-03-12」更改爲「12-Mar- 2016「如何將laravel Query Builder中的日期格式從「2016-03-12」更改爲「2016年3月12日」

$results = DB::table('customers as cust') 
     ->where('cust.id',$id) 
     ->select("cust.*","cust.cust_dob as dob") 
     ->first(); 

我應該使用laravel原始查詢。

我想這一點,

->select("cust.*","DATE_FORMAT(cust.cust_dob, '%d-%M-%Y') as formatted_dob") 

任何指導這個請。

+0

您可以使用原始查詢生成器。它看起來像普通查詢 – Exception

回答

2

Laravel使用Carbon的日期時間,所以你可以把它寫像下面的代碼:

$results = DB::table('customers as cust') 
      ->where('cust.id',$id) 
      ->select("cust.*","cust.cust_dob as dob") 
      ->first(); 
echo $results->dob->format('d-m-Y'); 
1

由於沒有使用除了原始查詢沒有辦法,我用的是這樣的。它爲我工作。

->select("cust.*", DB::raw("DATE_FORMAT(cust.cust_dob, '%d-%b-%Y') as formatted_dob")) 
0

Laravel給出了一個機會來確定訪問器/增變。你可以在這種情況下使用它,而不是通過查詢來完成。

我會在客戶模型類中添加方法

public function getCustDobAttribute($value) { 
    return //Format the value Which represent the value in database; 
} 

例子: 想象一下,你要檢索客戶的名字,你要得到它作爲第一承租人資本,其餘小。

public function getFirstNameAttribute($value) 
{ 
    return ucfirst($value); 
} 

參考:

https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators

4

嘗試這個

$results = DB::table('customers as cust') 
     ->where('cust.id',$id) 
     ->select(DB::raw('DATE_FORMAT("cust.cust_dob, "%d-%b-%Y") as formatted_dob') 
     ->first(); 
+0

完美,工作大。謝謝! –

相關問題