我需要一個快速的方法來判斷對象是否在集合中。我正在構建一個管理員可以爲用戶分配角色的模板。下面的陳述基本上是我想要完成的。在Laravel中,可以通過使用對象的主鍵來檢查對象是否位於集合中?
是在此角色集合中主鍵值爲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中有一種更簡單的方法可以通過使用對象的主鍵來判斷對象是否包含在集合中?
$ user-> roles() - > find(5)在角色之後添加()將查詢關係集。 – 2014-11-05 15:54:41