如果您单独使用 findOrFail 而不链接另一个方法 User::findOrFail(1),它将返回一个集合,但是一旦您开始添加其他条件,您必须为用户集合调用 ->get(),->first 或 ->last()对于单个用户对象,或者如果您使用 ->lists() 执行某些操作,您将获得一个数组。否则,您将获得构建器类,这是 {{ dd(User::where('id', 1)) }}
的示例
Builder {#1097 ▼
#query: Builder {#1096 ▶}
#model: User {#409 ▶}
#eagerLoad: array:1 [▶]
#macros: array:4 [▶]
#onDelete: Closure {#1102 ▶}
#passthru: array:12 [▶]
}
Builder 类就像一个从未执行过的准备好的语句。致电dd() 时,您应该会看到类似于以下内容的内容。
这会给你一个集合 {{ dd(\App\User::where('id', 1)->get()) }}
Collection {#1105 ▼
#items: array:1 [▼
0 => User {#1108 ▼
#cardUpFront: false
#dates: array:3 [▶]
#table: "users"
#fillable: array:2 [▶]
#hidden: array:2 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:17 [▶]
#original: array:17 [▶]
#relations: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
#forceDeleting: false
}
]
}
或使用 {{ dd(\App\User::where('id', 1)->first()) }}
获取单个对象
User {#1108 ▼
#cardUpFront: false
#dates: array:3 [▶]
#table: "users"
#fillable: array:2 [▶]
#hidden: array:2 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:17 [▶]
#original: array:17 [▶]
#relations: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
#forceDeleting: false
}
最后是一个数组 {{ dd(\App\User::where('id', 1)->lists('email','id')) }}
array:1 [▼
1 => "godfrey17@example.net"
]
希望这会有所帮助。