对集合只显示指定字段
$lists = UserService::tagList();
$lists = $lists->map(function ($item) {
return [
'id' => $item->id,
'tag_name' => $item->tag_name,
];
});
普通集合
$a = collect(['a','b']);
$a->push('c');
dd($a);
$a = collect(['id'=>1,'b'=>2]);
$a->put('c', '3');
dd($a);
$collection = collect([
['id'=>1, 'name'=>'Hardik'],
['id'=>2, 'name'=>'Harsukh'],
['id'=>3, 'name'=>'Bhagat'],
]);
$collection->push(['id'=>4, 'name'=>'vimal']);
$collection->all();
dd($collection);
新增元素
$action = Action::where('id',52)->first();
$action = collect($action);
$action->put('role','admin');
dd($action->toArray());
新增元素
$action = Action::whereIn('id',[52,56])->get();
$action->map(function ($post) {
$post['url'] = 'http://your.url/here';
return $post;
});
dd($action->toArray());
删除元素
$action = Action::select('id','action_name','start_date','end_date')->whereIn('id',[52,56])->get();
$action = $action->map(function ($post) {
unset($post['action_name']);
return $post;
});
dd($action->toArray());
新增元素
$param = 'test';
$action = Action::select('id','action_name','start_date','end_date')->whereIn('id',[52,56])->get();
$action->map(function($d) use($param) {
$d['starttime'] = $d['starttime'];
return $d;
});
dd($action->toArray());
https://www.itsolutionstuff.com/post/laravel-collection-push-and-put-exampleexample.html
删除元素
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$collection->forget(0);
$collection = $collection->values()->all();
dd($collection);
一个复杂一些的过滤加排序
$items=[
["num"=>17,"status"=>0,"grade"=>5],
["num"=>17,"status"=>2,"grade"=>4],
["num"=>7,"status"=>1,"grade"=>6],
["num"=>17,"status"=>0,"grade"=>3],
];
$ucsCollect=collect($items);
//过滤
$ucsCollect=$ucsCollect->filter(function ($item, $key) {
return $item['num'] > 14;
});
//倒序排序
$ucsList=$ucsCollect->sortByDesc(function ($item, $key) {
return $item['grade'];
//正序排序
})->sortBy(function ($item, $key) {
return $item['status'];
});
$ucsList = $ucsList->values()->all();
dd($ucsList);
如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术
转载请注明:laravel中数据库集合操作 出自老鄢博客 | 欢迎分享