2014-11-05 21 views
2

我需要一個快速的方法來判斷對象是否在集合中。我正在構建一個管理員可以爲用戶分配角色的模板。下面的陳述基本上是我想要完成的。在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中有一種更簡單的方法可以通過使用對象的主鍵來判斷對象是否包含在集合中?

+0

$ user-> roles() - > find(5)在角色之後添加()將查詢關係集。 – 2014-11-05 15:54:41

回答

8

使用$tmpUserRoles->contains(5)來檢查您的集合中是否存在主鍵5。 (請參閱http://laravel.com/docs/4.2/eloquent#collections

+2

對於版本5.1+,您可以使用' - > has()',例如'$ tmpUserRoles-> has(5)'https://laravel.com/docs/5.1/collections#method-has – Jon 2017-04-24 22:37:37

2

所選答案看起來像是有效的。

如果你想測試一個更可讀的方式,如果一個對象是laravel集合類的一個實例(或任何一般類),你可以使用PHP is_a()功能:

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

這不做你發現自己也想在你的問題描述中做的事情,但一般情況下可能會有所幫助。

+0

使用此代替'Illuminate \ Support \ Collection' '''var_dump(is_a(User :: active() - > get(),'Illuminate \ Support \ Collection')); // true var_dump(is_a(User :: pluck('id'),'Illuminate \ Support \ Collection')); // true''' – 2016-06-01 22:02:36

相關問題