0
点赞
收藏
分享

微信扫一扫

【Laravel笔记】9. 集合与模型


本文主要内容:


  • ​​9.1 创建与使用集合​​
  • ​​9.2 集合的常用方法​​
  • ​​9.3 扩展集合​​
  • ​​9.4 模型的数据集合​​
  • ​​9.5 附:集合的常用方法​​


9.1 创建与使用集合

什么是集合?


它是一种更具读取性和处理能力的数组封装。


比如,我们从数据库得到的数据列表,它就是一种集合;我们可以对这个返回的集合,进行各种操作。

$users = User::get();
dd($users);

输出结果我们可以看出,为集合:

Illuminate\Database\Eloquent\Collection {
......
}

除了数据库对象返回的数据集合之外,我们还可以自行创建数据集合:

//创建一个数据集合
$collection = collect(['张三', '李四', '王五', null]);

//使用 dd 查看它的类型
dd($collection);

//直接 return 可以返回
return $collection;

9.2 集合的常用方法

数据集合提供了大量的处理数据集合的方法,可链式调用。

数据集合的常用方法有​​数百个​​,篇幅有限,请见文末附录。

9.3 扩展集合

集合都是​​可宏扩展(macroable)​​​的,它允许你在执行时将其它方法添加到 ​​Collection​​​ 类。例如,通过下面的代码在 ​​Collection​​​ 类中添加一个 ​​toUpper​​ 方法:

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Collection::macro('toUpper', function () {
return $this->map(function ($value) {
return Str::upper($value);
});
});

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

//输出结果: ['FIRST', 'SECOND']

9.4 模型的数据集合


数据集合,就是已经将模型方法get()获取到的数据再进行处理。


首先,进行普通查询,得到的是一个集合:

$users = User::get();

然后可以对该 ​​$users​​ 集合进行再处理。示例如下:

1、​​map()​​方法,通过它可以实现类似访问器一样对字段进行处理的效果

//使用集合方法map 可以对输出的字段进行过滤
$users2 = $users->map(function ($user) {
$user->email = strtoupper($user->email);//转换成大写字母
return $user;
});
return [$users2];

最终输出的结果,邮箱全是大写的。

2、​​reject()​​ 方法,可以获取条件之外的数据内容;

$women = $users->reject(function ($user) {
return $user->gender != '女';
})->map(function ($user) {
return $user;
});
return [$women];

最终输出的结果,只包含​​gender=女​​ 的数据。

3、其他常用的集合方法列表:

//判断集合中是否包含指定的模型实例
return $users->contains(19);
return $users->contains(User::find(19));

//返回不在集合中的所有模型
return $users->diff(User::whereIn('id', [19,20,21])->get());

//返回给定主键外的所有模型
return $users->except([19,20,21]);

//集合也有find 方法
return $users->find(19);

//返回集合的数量
return $users->count();

//返回所有模型的主键
return $users->modelKeys();

//返回主键的所有模型
return $users->only([19,20,21]);

//返回集合中的唯一模型
return $users->unique();


其实这些方法,也是下面这些。可以参考附录。


9.5 附:集合的常用方法

下面将对一些常用的方法进行演示。


整理自:https://learnku.com/docs/laravel/8.x/collections/9390#method-all


1、all()

​all​​方法:返回代表集合的底层数组

示例:

collect([1, 2, 3])->all();
// [1, 2, 3]

2、avg() 或average()

average 是 avg 方法的别名。

​avg​​​ 方法:返回键的 ​​平均值​​:

$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20

$average = collect([1, 1, 2, 4])->avg();
// 2

3、chunk()

​chunk​​ 方法把集合分割成多个指定大小的较小集合:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->all();
// [[1, 2, 3, 4], [5, 6, 7]]

当使用如 ​​Bootstrap​​​那样的栅格系统时,该方法在 ​​视图​​​ 中相当有用。想象一下你有个想在栅格显示的 ​​Eloquent​​ 模型:

@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach

后边还有如下,有时间再慢慢补充吧……

chunkWhile

collapse

collect

combine

concat

contains

containsStrict

count

countBy

crossJoin

dd

diff

diffAssoc

diffKeys

dump

duplicates

duplicatesStrict

each

eachSpread

every

except

filter

first

firstWhere

flatMap

flatten

flip

forget

forPage

get

groupBy

has

implode

intersect

intersectByKeys

isEmpty

isNotEmpty

join

keyBy

keys

last

macro

make

map

mapInto

mapSpread

mapToGroups

mapWithKeys

max

median

merge

mergeRecursive

min

mode

nth

only

pad

partition

pipe

pipeInto

pluck

pop

prepend

pull

push

put

random

reduce

reject

replace

replaceRecursive

reverse

search

shift

shuffle

skip

skipUntil

skipWhile

slice

some

sort

sortBy

sortByDesc

sortDesc

sortKeys

sortKeysDesc

splice

split

splitIn

sum

take

takeUntil

takeWhile

tap

times

toArray

toJson

transform

union

unique

uniqueStrict

unless

unlessEmpty

unlessNotEmpty

unwrap

values

when

whenEmpty

whenNotEmpty

where

whereStrict

whereBetween

whereIn

whereInStrict

whereInstanceOf

whereNotBetween

whereNotIn

whereNotInStrict

whereNotNull

whereNull

wrap

zip



举报

相关推荐

9. Stateflow - 模型代码生成

9. 进程

9.单行与多行子查询

SQL笔记9.嵌入式SQL

9. 优化器

9. 回文数

9.因子数

9. 代码生成

0 条评论