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

New*_*der 0 php arrays laravel

我不确定这真的是一个 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
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

foreach($user->friends() as $friend) {
dd($friend);
}
Run Code Online (Sandbox Code Playgroud)

这是我做完后得到的:

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
}
Run Code Online (Sandbox Code Playgroud)

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

pat*_*cus 6

当您执行 . 时foreach,您只会看到一个条目,因为dd(). 请记住,它是“转储和死亡”,因此在第一次迭代时,您正在转储记录然后死亡。

试试这个:

foreach($user->friends() as $friend) {
    print_r($friend);
}
Run Code Online (Sandbox Code Playgroud)