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

2021-07-19 11:45 更新

有時候需要在查詢執(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(); 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號