在Laravel中,您可以使用对象';的主键


In Laravel can you check to see if an object is in a Collection by using the object's primary key?

我需要一种快速的方法来判断对象是否在集合中。我正在构建一个模板,管理员可以在其中为用户分配角色。下面的陈述基本上就是我想要实现的。

是此角色集合中主键值为5的角色。

我正在做的事情(显然被简化为一个文件):

<?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;
    }
}

在数组上循环只是为了创建一个以主键为索引的相同数组,这似乎是在浪费时间。在Laravel中,有没有一种更简单的方法可以通过使用对象的主键来判断对象是否包含在集合中?

使用$tmpUserRoles->contains(5)检查集合中是否存在主键5。(请参见http://laravel.com/docs/4.2/eloquent#collections)

所选答案看起来很有效。

如果您想要一种更可读的方式来测试对象是否是laravel集合类(或一般任何类)的实例,您可以使用phpis_a()函数:

// This will return true if $user is a collection
is_a($user, "Illuminate'Database'Eloquent'Collection");

这并不能完成你在问题描述中想要做的发现,但总体来说可能会有所帮助。