2016-11-12 290 views
1

我在集合https://laravel.com/docs/5.3/collections#method-contains上使用Laravel contains方法。但它不適合我。Laravel集合包含

foreach ($this->options as $option) { 
    if($options->contains($option->id)) { 
     dd('test'); 
    } 
} 

dd($options);看起來是這樣的:

Collection {#390 
    #items: array:1 [ 
    0 => array:3 [ 
     0 => array:7 [ 
     "id" => 10 
     "slug" => "test" 
     "name" => "test" 
     "poll_id" => 4 
     "created_at" => "2016-11-12 20:42:42" 
     "updated_at" => "2016-11-12 20:42:42" 
     "votes" => [] 
     ] 
     1 => array:7 [ 
     "id" => 11 
     "slug" => "test-1" 
     "name" => "test" 
     "poll_id" => 4 
     "created_at" => "2016-11-12 20:42:42" 
     "updated_at" => "2016-11-12 20:42:42" 
     "votes" => [] 
     ] 
     2 => array:7 [ 
     "id" => 12 
     "slug" => "test-2" 
     "name" => "test" 
     "poll_id" => 4 
     "created_at" => "2016-11-12 20:42:42" 
     "updated_at" => "2016-11-12 20:42:42" 
     "votes" => [] 
     ] 
    ] 
    ] 
} 

dd($option->id);結果10

什麼可能是錯的?或者,還有更好的方法?

+0

代碼應該作爲文本張貼,而不是圖片請... – Blag

+0

@布拉格改變了它! – Jamie

回答

6

您應該將一個鍵/值對傳遞給contains方法, 將確定給定對是否存在於集合中。

你應該以這種方式使用contains()方法:

foreach ($this->options as $option) { 
    // Pass key inside contains method 
    if($option->contains('id', $option->id)) { 
     dd('test'); 
    } 
} 

希望這有助於

1
foreach ($this->options as $option) { 
    if(!$options->flatten(1)->where('id',$option->id)->isEmpty()) { 
     dd('test'); 
    } 
} 
1

使用下,它告訴Laravel要匹配的 '身份證':

$options->contains('id', $option->id); 

Docs