在Laravel 5 Collection中,如何返回对象数组而不是数组数组? [英] In a Laravel 5 Collection how do you return an array of objects instead of an array of arrays?

查看:60
本文介绍了在Laravel 5 Collection中,如何返回对象数组而不是数组数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5和Blade模板.在视图中,我要遍历Model对象的数组,而不是数组的数组. 如果我确实想遍历一个数组,我将执行以下操作,该操作将按预期进行:

I am using Laravel 5 and a Blade template. In a view I want to iterate over an array of Model objects, not an array of arrays. If I did want to iterate over an array of arrays I would do the following, which works as expected:

$models = Foo::where('id', '>', 5)->get();
return view('home.index', ['models' => $models->toArray()]);

但是我想要一个具有可访问属性的对象数组.如果我要跑步:

However I want an array of objects with accessible properties. If I were to run:

$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

不仅不填充项目"对象中的模型的属性.

Not only is the Model in an 'items' object the properties are not filled.

在一种观点下,我想做这样的事情:

In a view I would like to do something like this:

@foreach ($models as $model)
    @include('_partial') {
        'id' => $model->id,
        'foo' => $model->foo,
    }
@endforeach

如何获取模型数组而不是模型数组?

How do I get an array of Models instead of an array of an array of Models?

推荐答案

找出了问题所在.我在模型中明确定义了属性. Laravel以一种特殊的方式使用__get(),无论明确定义的属性如何,传递的参数都会被覆盖.

Figured out the problem. I was explicitly defining the attributes in the Model. Laravel uses __get() in a particular way which causes passed parameters to be overridden whatever attributes are explicitly defined.

换句话说,我在局部中获取空值,因为传递给局部的信息已被覆盖.

In other words, I was getting null values in the partial because the info I was passing to the partial was overridden.

这篇关于在Laravel 5 Collection中,如何返回对象数组而不是数组数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆