$phone_Id = $request->get('q');
$colors = Phone::find($phone_Id)->color->toArray();
dd($colors);
array:2 [▼
0 => array:6 [▼
"id" => 8
"name" => "red"
"value" => "#fb6250"
"created_at" => "2019-05-29 01:42:51"
"updated_at" => "2019-05-29 01:42:51"
"pivot" => array:4 [▼
"phone_id" => 1
"color_id" => 8
"created_at" => "2019-05-29 01:42:51"
"updated_at" => "2019-05-29 01:42:51"
]
]
1 => array:6 [▼
"id" => 11
"name" => "blue"
"value" => "#202020"
"created_at" => "2019-05-29 01:42:51"
"updated_at" => "2019-05-29 01:42:51"
"pivot" => array:4 [▼
"phone_id" => 1
"color_id" => 11
"created_at" => "2019-05-29 01:42:51"
"updated_at" => "2019-05-29 01:42:51"
]
]
]
array:2 [▼
0 => array:2 [▼
"id" => 8
"text" => "red"
]
1 => array:2 [▼
"id" => 11
"text" => "blue"
]
]
$data = [];
foreach ($colors as $key => $val) {
$data[$key]['id'] = $val->id;
$data[$key]['text'] = $val->name;
}
dd($data);
array:2 [▼
0 => array:2 [▼
"id" => 8
"text" => "red"
]
1 => array:2 [▼
"id" => 11
"text" => "blue"
]
]
我想知道laravel中对于这种需求是否有更好,更漂亮的实现方式?
答案 0 :(得分:3)
$colors = Phone::find($phone_Id)->color;
$colors->transform(function ($color) {
return [
'id' => $color->id,
'text' => $color->name,
];
});
编辑::感谢您提供正确的答案和支持,但我想指出的是,OP使用查询生成器的->get(..)
并重命名了列,从而提供了一种更为优雅的解决方案:
$colors = Phone::find($phone_Id)->color()->get(['id', 'name as text'])->toArray();
答案 1 :(得分:0)
使用// From Previous View Controller
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "ShowSection" {
let controller = segue.destination as! SectionsViewController
controller.context = context
let button = sender as! UIButton
let section = photos[button.tag].place
controller.selectedSection = section!
// This passes on a String
}
}
// Saving pins to the map
if let annotationView = annotationView {
annotationView.annotation = annotation
let button = annotationView.rightCalloutAccessoryView as!
if let index = photos.firstIndex(of: annotation as! Photo) {
button.tag = index
}
// In the Sections View Controller (i.e. the second VC)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections = fetchedRC.sections {
let currentSection = sections[section]
return currentSection.numberOfObjects
} else {
return 0
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return selectedSection
}
尝试这个。
select('id', 'name')
答案 2 :(得分:0)
Laravel集合具有->only()
方法和->map()
,可以像这样使用:
$colors = Phone::find($phone_Id)->color()->only(['id', 'name'])toArray();
$colors->map(function($color) {
$color->text = $color->name;
unset($color->text);
})