Laravel 8 查詢時(shí)類型轉(zhuǎn)換

2021-07-19 11:45 更新

有時(shí)候需要在查詢執(zhí)行過程中對(duì)特定屬性進(jìn)行類型轉(zhuǎn)換,例如需要從數(shù)據(jù)庫表中獲取數(shù)據(jù)的時(shí)候。舉個(gè)例子,請(qǐng)參考以下查詢:

use App\Models\Post;
use App\Models\User;

$users = User::select([
    'users.*',
    'last_posted_at' => Post::selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->get(); 

在該查詢獲取到的結(jié)果集中, last_posted_at 屬性將會(huì)是一個(gè)字符串。假如我們?cè)趫?zhí)行查詢時(shí)進(jìn)行 date 類型轉(zhuǎn)換將更方便。你可以通過使用 withCasts 方法來完成上述操作:

$users = User::select([
    'users.*',
    'last_posted_at' => Post::selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->withCasts([
    'last_posted_at' => 'datetime'
])->get(); 
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)