如何访问Collection中的特定属性?

时间:2017-01-13 13:09:52

标签: php mysql laravel collections eloquent

我想从练习表中访问name属性,但我收到了Collections。我的代码看起来像。

$

,结果看起来像

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

dd($practice);

有没有办法,所以我可以得到“DJ和Charlie Eye Associates”这个名字。我使用了withThrashed方法,因为这个条目在练习表中被软删除了。

5 个答案:

答案 0 :(得分:2)

您可以使用foreach循环

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

或者您可以将集合转换为数组

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

$collection->first()->name;

希望这有助于你。

询问是否有任何查询

答案 1 :(得分:2)

首先,您需要从集合中获取对象,然后您可以获取该对象的任何属性:

$practice->first()->name;

或者:

$practice[0]->name;

答案 2 :(得分:1)

您可以通过使用此

来实现此目的
dd($practice[0]->name);

或者,如果您知道您的查询只返回一个对象,则可以使用->first()代替->get(),然后就可以使用。

dd($practice->name);

->first()给出第一个对象

->get()提供了一系列对象。

答案 3 :(得分:1)

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

dd($practice);

虽然这非常丑陋,你可能已经阅读了Collections:你的陈述完全正是Laravel所说的。

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

答案 4 :(得分:0)

如果find()是主键,请使用id,您只需返回练习。

 $practice = Practice::withTrashed()->find($appointment->practice_id);

https://laravel.com/docs/5.3/eloquent#retrieving-single-models

相关问题