问题是当dd($ responsablle或$ type)时仅显示first_name 我需要选择first_name和id
public function create(){
$responsable = User::all()->pluck('first_name','id');
$type = EventType::all()->pluck('type','id');
return view ('backend.event.create', compact('responsable', 'type'));
}
答案 0 :(得分:1)
首先在生成器上使用pluck
,而不是检索所有记录及其所有字段,然后pluck
从“集合”中获取字段:
$responsable = User::pluck('first_name', 'id');
$type = EventType::pluck('type', 'id');
第二个争论是您要作为“集合” /“数组”键入依据的字段。 id
部分是元素的键:
foreach ($responsable as $key => $value) {
// $key is the 'id' field
// $value is the 'first_name'
}
foreach ($type as $key => $value) {
// $key is the 'id' field
// $value is the 'type'
}
或者更有用的命名方式:
foreach ($responsable as $id => $first_name) { ... }
foreach ($type as $id => $type) { ... }
Laravel 5.8 Docs - Query Builder - Retrieving Results - Retrieving A List Of Column Values pluck
Laravel 5.8 Docs - Collections - Available Methods - pluck
pluck
答案 1 :(得分:0)
说实话,您实际上不必在这里使用pluck()
。如果仅限制通过->select()
返回的列,则会收到记录,其属性仅限于指定的列:
$users = User::select('first_name', 'id')->get();
$types = EventType::select('type', 'id')->get();
现在,当遍历这些内容时,您将可以访问first_name
,id
和type
,id
:
foreach($users AS $user){
echo $user->id."|".$user->first_name;
}
foreach($types AS $type){
echo $type->type."|".$type->id;
}
请注意,这确实返回了User
和EventType
的完整模型,但是强制转换为array
会将其简化为每个记录的关联数组:
$users = User::select('first_name', 'id')->get()->toArray();
dd($users);
/* array:2 [▼
0 => array:2 [▼
"first_name" => "Bob"
"id" => "1"
]
1 => array:2 [▼
"first_name" => "Mike"
"id" => "2"
]
] */
$types = EventType::select('type', 'id')->get()->toArray();
dd($types);
/* array:2 [▼
0 => array:2 [▼
"type" => "Red"
"id" => "1"
]
1 => array:2 [▼
"type" => "Blue"
"id" => "2"
]
] */
然后,在循环时,您可以进行类似的访问:
foreach($users AS $user){
echo $user["id"]."|".$user["first_name"];
}
// Or, $users[0]["first_name"], etc.
foreach($types AS $type){
echo $type["type"]."|".$type["id"];
}
// Or, $types[0]["type"], etc.