2016-11-12 160 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