采摘 Laravel Eloquent 集合差异总是 returns 一个空集合

Plucked Laravel Eloquent Collection Diff always returns an empty collection

我想看看我在使用两个不同的数据集抓取数据时是否有不同的ID。不是我需要的,但是例如,我想查看所有订购产品 A 的人和所有订购产品 B 的人,然后查看哪些人只订购了 A 或 B。

所以,我有 $Collection1,当转储时它看起来像这样:

Illuminate\Support\Collection {#3031 ▼
  #items: array:1 [▼
    0 => 14066
  ]
  #escapeWhenCastingToString: false
}

然后我的 $Collection2 看起来像这样:

Illuminate\Support\Collection {#3000 ▼
  #items: array:3 [▼
    2 => 13147
    0 => 14066
    1 => 14066
  ]
  #escapeWhenCastingToString: false
}

我希望当我这样做时 $Collection1->diff($Collection2) 我会得到一个包含 13147 作为其中一项的集合。

我得到的是这样的:

Illuminate\Support\Collection {#2998 ▼
    #items: []
    #escapeWhenCastingToString: false
}

知道我做错了什么吗?

非常感谢。

如 Laravel 文档中所述:

"The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection"

https://laravel.com/docs/9.x/collections#method-diff

因此,将一个空集合与另一个集合进行比较总是 return 为空,就像您的情况一样。然后你应该比较确实有值的集合以获得你想要的结果

$Collection1->diff($Collection2) 表示 (collection1 - collection2)

但你不会(collection1 - collection2) + (collectio2 - collection1)

这样写:

$diff1 = $Collection1->diff($Collection2);
$diff2 = $Collection2->diff($Collection1);
$result = $diff1->merge($diff2);