簡體   English   中英

Laravel Eloquent如何從數組中獲取結果

[英]Laravel Eloquent How to fetch results from array

我一直在花很多時間尋找這個。

我是Laravel的新手,(來自CodeIgniter),除非有必要,否則我會嘗試以Laravel的方式進行操作,而不是在任何地方使用純PHP / SQL。

$role_id = Role::select('role_id')
                    ->where('type','Admin')
                    ->get();
    var_dump($role_id);

我正在嘗試獲取$ role_id。

var_dump給了我這個。

object(Illuminate\Database\Eloquent\Collection)#249 (1) { ["items":protected]=> array(1) { [0]=> object(App\Role)#252 (26) { ["connection":protected]=> string(5) "mysql" ["table":protected]=> string(5) "roles" ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(1) { ["role_id"]=> int(99) } ["original":protected]=> array(1) { ["role_id"]=> int(99) } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } } } }

我期望只是一個mysql結果行而不是這個。

我正在尋找的只是這個["role_id"]=> int(99)

我缺少直接獲取此功能的函數,但無法從文檔中找到它。

$role_id->role_id給我找不到財產。

您的項目帶有get方法。 由於這個原因,無法訪問role_id。

如果要一條記錄,可以使用first而不是get方法。

您可以使用dd()函數。

$role_id = Role::select('role_id')
                ->where('type','Admin')
                ->first();
dd($role_id);

你可以這樣做:

$role_id = Role::all(['role_id'])->where('type','Admin')->first(); or Role::where('type', 'Admin');

Instead of var_dump you can use dd($role_id) or var_dump($role_id), it dies and dumps at the same time .

使用->first()代替->get() get()返回collection。

這是正確的方法。

$response = Role::select('role_id')
                       ->where('type','Admin')
                       ->first();
        $admin_id = $response->role_id; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM