2017-01-13 76 views
1

我想從練習表訪問名稱屬性,但我得到的集合。我的代碼看起來像。如何訪問集合中的特定屬性?

$practice = Practice::withTrashed()->where('id',$appointment->practice_id)->get(); 

dd($practice); 

和結果如下

Collection {#697 
    #items: array:1 [ 
    0 => Practice {#698 
     #dates: array:1 [ 
     0 => "deleted_at" 
     ] 
     #fillable: array:2 [ 
     0 => "name" 
     1 => "email" 
     ] 
     #connection: null 
     #table: null 
     #primaryKey: "id" 
     #keyType: "int" 
     #perPage: 15 
     +incrementing: true 
     +timestamps: true 
     #attributes: array:7 [ 
     "id" => 42 
     "name" => "DJ and Charlie Eye Associates" 
     "email" => "[email protected]" 
     "created_at" => "0000-00-00 00:00:00" 
     "updated_at" => "2017-01-13 06:29:14" 
     "liferay_id" => 57238 
     "deleted_at" => "2017-01-13 06:29:14" 
     ] 
     #original: array:7 [ 
     "id" => 42 
     "name" => "DJ and Charlie Eye Associates" 
     "email" => "[email protected]" 
     "created_at" => "0000-00-00 00:00:00" 
     "updated_at" => "2017-01-13 06:29:14" 
     "liferay_id" => 57238 
     "deleted_at" => "2017-01-13 06:29:14" 
     ] 
     #relations: [] 
     #hidden: [] 
     #visible: [] 
     #appends: [] 
     #guarded: array:1 [ 
     0 => "*" 
     ] 
     #dateFormat: null 
     #casts: [] 
     #touches: [] 
     #observables: [] 
     #with: [] 
     #morphClass: null 
     +exists: true 
     +wasRecentlyCreated: false 
     #forceDeleting: false 
    } 
    ] 
} 

有沒有辦法做的,所以我可以得到名爲「DJ和查理眼科協會」。我和Thrashed方法一起使用,因爲這個條目在練習表中被軟刪除。

回答

2

首先,你需要從集合的對象,那麼你就可以得到那個對象的任何屬性:

$practice->first()->name; 

或者:

$practice[0]->name; 
2

您可以使用foreach循環

foreach($collection as $collect){ 
    dd($collect->name); 
} 

或者你可以轉換成集合陣列

$array = $collection->toArray(); 
dd($array[0]->name); 

$collection->first()->name; 

希望這可以幫助你。

詢問是否有任何疑問

+0

它應該工作.. –

1

你可以簡單地通過使用此

dd($practice[0]->name); 

或者,如果你知道你的查詢將返回只有一個對象,你可以代替->get()使用->first()然後得到這個你可以用。

dd($practice->name); 

->first()給出第一對象

->get()給出對象數組。

1
$practice = Practice::withTrashed()->where('id',$appointment->practice_id)->get()->get('name'); 

dd($practice); 

雖然這是令人難以置信的醜陋你可能會閱讀Collections:你的陳述正在做Laravel所說的。

https://laravel.com/docs/5.3/collections

相關問題