在 Laravel 中,您可以使用对象的主键来检查对象是否在集合中吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26761231/
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
In Laravel can you check to see if an object is in a Collection by using the object's primary key?
提问by TheNatureBoy
I need a quick way to tell if an object is in a collection. I'm building a template where an admin can assign a User a role. The statement below is essentially what I'm trying to accomplish.
我需要一种快速的方法来判断一个对象是否在集合中。我正在构建一个模板,管理员可以在其中为用户分配角色。下面的陈述基本上是我想要完成的。
IS the role with a primary key value of 5 in this collection of Roles.
是此角色集合中主键值为 5 的角色。
What I'm doing (obviously dumbed down into one file):
我在做什么(显然简化为一个文件):
<?php
// The user
$user = User::find(1);
// Array of roles the user is associated with. Fetched via a pivot table
$tmpUserRoles = $user->roles->toArray();
// Rebuilds the values from $tmpUserRoles so that the array key is the primary key
$userRoles = array();
foreach ($tmpUserRoles as $roleData) {
$userRoles[$roleData['role_id']] = $roleData;
}
// This loop is used in the view. Once again, this is dumbed down
foreach ($Roles as $role) {
if (isset($userRoles[$role->role_id]) {
echo $user->firstName.' is a '.$role->label;
} else {
echo $user->firstName.' is not a '.$role->label;
}
}
Looping over an array just to create an identical array with the primary key as an index seems like a big waste of time. Is there an easier way in Laravel to tell if an object is contained in a collection by using the object's primary key?
循环遍历数组只是为了创建一个以主键作为索引的相同数组似乎是在浪费时间。Laravel 中是否有更简单的方法通过使用对象的主键来判断对象是否包含在集合中?
回答by damiani
Use $tmpUserRoles->contains(5)
to check if primary key 5
exists in your collection.
(See http://laravel.com/docs/4.2/eloquent#collections)
使用$tmpUserRoles->contains(5)
检查,如果主键5
的集合中存在。(见http://laravel.com/docs/4.2/eloquent#collections)
回答by Chris Schmitz
The selected answer looks like it works.
所选答案看起来有效。
If you want a more readable way of testing if an object is an instance of the laravel collection class (or any class in general) you could use the php is_a()
function:
如果您想要一种更易读的方式来测试对象是否是 laravel 集合类(或任何一般类)的实例,您可以使用 phpis_a()
函数:
// This will return true if $user is a collection
is_a($user, "Illuminate\Database\Eloquent\Collection");
This doesn't do the finding that you're also wanting to do in your question description, but it could be helpful in general.
这并不能完成您在问题描述中也想要做的发现,但总的来说它可能会有所帮助。