Laravel 8 從數(shù)據(jù)表中獲取單行或單列

2021-07-19 11:10 更新

如果你只需要從數(shù)據(jù)表中獲取一行數(shù)據(jù),你可以使用 first 方法。該方法返回一個 stdClass 對象:

$user = DB::table('users')->where('name', 'John')->first();

echo $user->name; 

如果你甚至不需要整行數(shù)據(jù),則可以使用 value 方法從記錄中獲取單個值。該方法將直接返回該字段的值:

$email = DB::table('users')->where('name', 'John')->value('email'); 

如果是通過 id 字段值獲取一行數(shù)據(jù),可以使用 find 方法:

$user = DB::table('users')->find(3); 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號