Laravel 集合过滤以避免空记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51879957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel collection filtering to avoid null records
提问by dev1234
is there an inbuilt way to loop through collections and return only the objects that are meeting a specific condition?
是否有内置的方法来循环遍历集合并仅返回满足特定条件的对象?
like skip all records that has $user->role === null
就像跳过所有有的记录 $user->role === null
回答by Haider Ali
You can use filter
method to filter the users against your condition
您可以使用filter
方法根据您的条件过滤用户
$filteredUsers = $users->filter(function ($user, $key) {
return $user->role != null;
});
回答by Tim Lewis
You actually don't even need the ->filter
method if you're using Eloquent
. If role
is a relationship of your User
model, you can simply call:
事实上,你甚至都不需要了->filter
,如果你使用的方法Eloquent
。如果role
是你的User
模型的关系,你可以简单地调用:
$users = User::has("role")->get();
This will automatically return only Users that have a role
, or where $user->role
is not null.
这将自动仅返回具有role
, 或 where$user->role
不为空的用户。
回答by Zakaria Acharki
You could use the whereNotNull()
method that verifies if the value of the given column is NULL :
您可以使用whereNotNull()
验证给定列的值是否为 NULL 的方法:
User::whereNotNull('role')->get();
回答by Davit
This is what you wont. See docs https://laravel.com/docs/5.5/collections#method-where
这是你不会的。请参阅文档https://laravel.com/docs/5.5/collections#method-where
$result = $collection->where('rule', null);
回答by Azraar Azward
you could use reject, filter
functions to achieve this
你可以使用reject, filter
函数来实现这一点
$users = User::all();
$users = User::all();
$users->each(function($users) {
$users->roles->reject(function($role) {
return $role->rule === null;
});
});
Please refer to this to use filter -> http://laravel.com/docs/5.6/collections#method-filter
请参考此使用过滤器 -> http://laravel.com/docs/5.6/collections#method-filter
回答by OtienoJulie
You can wrap everything within if($row->filter()->isNotEmpty())
this has worked for me in the past
你可以把所有的东西都包装起来,if($row->filter()->isNotEmpty())
这在过去对我有用
回答by Priyanka
For laravel collection, whereStrict
is perfect for filtering to avoid null records.
对于 Laravel 集合,whereStrict
非常适合过滤以避免空记录。
Because whereStrict compares value + datatype.
因为 whereStrict 比较值 + 数据类型。
$result = $collection->whereStrict('role', null);