拉拉维尔系列包含

2022-08-30 16:57:18

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

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

可能出了什么问题?还是有更好的方法?


答案 1

应将键/值对传递给 contains 方法,该方法将确定集合中是否存在给定的对。以这种方式使用 contains() 方法:

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

答案 2

使用以下命令,告诉Laravel您想要匹配“id”:

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

文档


推荐