[Laravel 5.3 新功能] 6. Collection::where 高级操作

[Laravel 5.3 新功能] 6. Collection::where 高级操作#

说明#

此文章是 [Laravel 5.3 新功能] 系列的第六篇文章,Collection::where 高级操作。

[Laravel 5.3 新功能] 系列完整文章列表请见:分享:[Laravel 5.3 新功能] 系列文章

where () 介绍#

如果你想过滤 laravel collection 中的指定数据,你一般会使用 filter () 或 reject (),比如:

$vips = $people->filter(function ($person) {
    return $person->status === 'vip';
});

$nonVips = $people->reject(function ($person) {
    return $person->status === 'vip';
});

你可能不知道 where() 方法能通过更少的代码来完成上面的逻辑:

$vips = $people->where('status', 'vip');

5.3 之前,where () 默认使用严格模式(即使用全等判断 ===)来验证数据是否符合需求。

在 5.3 之后,where () 使用松散模式(即使用 ==)来验证数据是否符合需求,但你也可以手动指定比较操作符:

$nonVips = $people->where('status', '!==', 'vip');
$popularPosts = $posts->where('views', '>', 500);
$firstTimeUsers = $people->where('logins', '===', 1);

你可以查看这部分的 源代码 看看作者是怎么实现这个逻辑的。

链接#

本帖已被设为精华帖!
本帖由系统于 8年前 自动加精
monkey
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。