【发布时间】:2015-04-30 20:38:58
【问题描述】:
我正在使用 Laravel 5 和 Blade 模板。在一个视图中,我想遍历模型对象数组,而不是数组数组。 如果我确实想遍历数组数组,我会执行以下操作,这可以按预期工作:
$models = Foo::where('id', '>', 5)->get();
return view('home.index', ['models' => $models->toArray()]);
但是,我想要一组具有可访问属性的对象。如果我要跑步:
$models = Foo::where('id', '>', 5)->get();
return view('home.index', ['models' => $models->all()]);
var_dump 看起来像这样:
object(Illuminate\Support\Collection)[164]
protected 'items' =>
array (size=3)
0 =>
object(App\Foo)[172]
public 'id' => null
public 'foo' => null
private 'created_at' => null
private 'updated_at' => null
protected 'connection' => null
protected 'table' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=4)
'id' => int 1
'foo' => string 'Foo!' (length=4)
'created_at' => string '2015-02-27 15:44:09' (length=19)
'updated_at' => null
不仅“项目”对象中的模型没有填充属性。
在一个视图中,我想做这样的事情:
@foreach ($models as $model)
@include('_partial') {
'id' => $model->id,
'foo' => $model->foo,
}
@endforeach
如何获取模型数组而不是模型数组的数组?
【问题讨论】:
-
不要在 $models 上调用 toArray()。
-
@Carter 我没有打电话给
toArray()。如果我想要不同的结果,这只是一个可行的例子。 -
我听不懂你想说的话。正如 Bogdan 回答的那样,只需将 Collection (模型)传递给视图就足够了;无需在查询结束时调用 toArray()。
标签: php laravel iterator laravel-5