W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
有時候需要在查詢執(zhí)行過程中對特定屬性進行類型轉(zhuǎn)換,例如需要從數(shù)據(jù)庫表中獲取數(shù)據(jù)的時候。舉個例子,請參考以下查詢:
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
屬性將會是一個字符串。假如我們在執(zhí)行查詢時進行 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號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: