laravel - 如何确定我的 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);
}
解决方案
这很简单。您的方法是正确且有效的,只是您还没有一路走好。
// 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.
}
推荐阅读
- php - Jscroll加载相同的内容
- python - 如何添加两个字典
- jenkins - 分支中特定文件夹的 Jenkins WebHook URL
- php - PHP 只允许字符串中的特定单词
- django-models - 使用 Django 计算 TextField 字符数
- python-3.x - 即使我初始化了局部和全局变量,也尝试使用未初始化的值错误
- c# - 如何在asp.net c#中将json数据绑定到gridview?
- go - 包源之间的循环依赖
- npm - 如何让 npm 始终获取最后一个预发布版本?
- angular - 尝试在 azure 应用程序中更新 nodejs 版本时出现问题。无法在 azure 中为应用程序执行构建