当我调用 Laravel 的 dd() 函数时,脚本执行/foreach() 循环停止

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

当我像

dd()
那样调用
dd($user->friends());
(死亡并转储)时,我只获得集合中第一条记录的输出。

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

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
}

但是当我在不循环的情况下转储集合时,我可以看到多条记录。

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 错误还是与集合有关?

php laravel foreach dump dd
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.