首页 > 解决方案 > 如何确定我的 laravel 收藏是否匹配

问题描述

我试图找出我的旧产品是否与我的新产品完全匹配。例如,我有一个包含 5 个旧产品的 laravel 集合和另一个包含 5 个新产品的集合,我需要知道 5 个旧产品是否与 5 个新产品匹配,如果它们成功则失败,如果新产品也比旧产品多,但旧产品仍然匹配新产品,那么它也是成功的

这是我的代码

    public function changeProducts(Category $category)
    {
        $old_category = $category;
        $old_products = Product::where('category_id', $old_category->id)->get();

        $new_category = Category::find(request('category'));
        $new_products = Product::where('category_id', $new_category->id)->get();

        $diff = $old_products->diff($new_products);
        dd($diff);
    }

标签: laravellaravel-8

解决方案


这很简单。您的方法是正确且有效的,只是您还没有一路走好。

// This will return empty if all the data in old
// collection matches the new collection, even if the new
// collection has more data.
$diff = $old_products->diff($new_products);

if (count($diff) > 0) {
    echo "They do no match";   // write your code.
}
else {
    echo "They much, doesn't matter if new collection has more.";  // write your code.
}

推荐阅读