php Laravel:如何通过 id 从集合中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28077817/
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: how to remove item from Collection by id
提问by Phil
I want to remove the admin user from my collection. I know its the primary key in the table (id) is 1. But when I use forget(1)
it deletes the array element in the collection starting from 0. How do I remove the item from the collection by the id?
我想从我的收藏中删除管理员用户。我知道它在表 (id) 中的主键是 1。但是当我使用forget(1)
它时,它会删除集合中从 0 开始的数组元素。如何通过 id 从集合中删除该项目?
// Grab all the users
$users = User::all(); //$this->user; use to return array not Laravel Object
if($users->find(1)->hasRole('admin'))
$users->forget(0);
回答by trm42
As such bencohenbaritone's answer is better way to resolve this problem, I have to add that Laravel Eloquent Collection has method except()
, which can remove Eloquent objects from the collection by primary keyinstead of forget()
. The latter one removes by collection index key (like array[i]
) and not by primary key.
由于bencohenbaritone的回答是解决这个问题的更好方法,我必须补充一点,Laravel Eloquent Collection 有方法except()
,它可以通过主键而不是forget()
. 后一个通过集合索引键(如array[i]
)而不是主键删除。
So you can write something like (sorry about the bad example, my own use case is too different to be useful for others):
所以你可以写一些类似的东西(抱歉这个不好的例子,我自己的用例太不同了,对其他人没有用):
$admin_user_id = 20;
$users = User::all();
$users_without_admin = $users->except($admin_user_id);
回答by bthecohen
Instead of trying to delete an item from the collection, it would be better to never select it in the first place.
与其尝试从集合中删除一个项目,不如一开始就不要选择它。
You could add a constraint to your DB query like this:
您可以像这样向数据库查询添加约束:
$users = User::where('role', '!=', 'admin')->get();
(It could be slightly different depending on how roles are defined in your schema).
(这可能会略有不同,具体取决于您的架构中角色的定义方式)。
If you are using a more complex schema with a separate roles
table and user_role
table, you can query like this:
如果您使用具有单独roles
表和user_role
表的更复杂模式,您可以这样查询:
$users = User::whereHas('roles', function($q){
$q->where('role', '!=', 'admin');
})->get();
It's a bad idea to rely on the admin user always being the first item in the collection. What if later you want to have multiple admin users, or to sort the user list by registration date? If you really want to remove admin from the collection, Eloquent has built-in filtering functionality:
依赖 admin 用户始终是集合中的第一个项目是一个坏主意。如果以后您想拥有多个管理员用户,或者按注册日期对用户列表进行排序,该怎么办?如果你真的想从集合中删除 admin,Eloquent 有内置的过滤功能:
$usersWithoutAdmins = $users->filter(function($user)
{
return !$user->hasRole('admin');
});