W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
有時(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();
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: