对象数组,不会在 laravel 中的 foreach 中循环

问题描述 投票:0回答:2

我不确定这真的是一个 Laravel 问题,但是,当我 dd(die and dump) 这个 dd($user->friends()); 时我得到以下信息。我确实注意到这是一个集合。我不确定这是否意味着不同。但我认为它仍然应该是一系列项目。第一个用户位于 [0] 标记,下一个用户位于 [1],等等...

Collection {#184 ▼
  #items: array:2 [▼
    0 => User {#189 ▼
      #table: "users"
      #fillable: array:7 [▶]
      #hidden: array:3 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:11 [▶]
      #original: array:13 [▶]
      #relations: array:1 [▶]
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => User {#190 ▼
      #table: "users"
      #fillable: array:7 [▶]
      #hidden: array:3 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:11 [▶]
      #original: array:13 [▶]
      #relations: array:1 [▶]
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
}

那么当我尝试做类似的事情时:

foreach($user->friends() as $friend) {
dd($friend);
}

这就是我这样做后得到的:

User {#189 ▼
  #table: "users"
  #fillable: array:7 [▶]
  #hidden: array:3 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:11 [▶]
  #original: array:13 [▶]
  #relations: array:1 [▶]
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

我希望它循环遍历所有用户,而不仅仅是第一个用户。它这样做是有原因的吗?我做的 foreach 错误还是与集合有关?

php arrays laravel
2个回答
8
投票

当您执行

foreach
时,由于
dd()
,您只能看到一个条目。请记住,这是“转储并死亡”,因此在第一次迭代中,您将转储记录然后死亡。

试试这个:

foreach($user->friends() as $friend) {
    dump($friend);
}

-1
投票

如果您只想将其视为数组,请先在集合上使用 toArray 。例如:

$friends = $user->friends()->toArray();
foreach($friends as $friend){
 ...some stuff...
}

否则,请按照此处的文档使用 laravel 集合的功能: http://laravel.com/docs/5.2/collections

© www.soinside.com 2019 - 2024. All rights reserved.