【问题标题】:how to compare two collection and get match records如何比较两个集合并获取匹配记录
【发布时间】:2020-04-03 12:56:52
【问题描述】:

我正在使用 Laravel,我有两个包含产品 ID 的不同集合

第一个是colorProduct,第二个是tagProduct

所以我想比较这两者并只获得相同的产品 ID,我该怎么做呢?

$colorProducts = Color::where('code', $request->color)->get()->first()->products;

$tagProducts = $tag->products->where('shop_id', $shop->id);

$colorAndTagProducts = collect();

foreach ($colorProducts->toBase()->merge($tagProducts)->unique('id')->groupBy('id') as $allProducts) {
    if ($allProducts->count() >= 1) {
        $colorAndTagProducts[] = $allProducts->first();
    }
}

这里

$colorAndTagProducts

给我所有记录来自两个集合,但我只想要相同的记录

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    我不知道,如果我理解正确,但也许是这样? 我想颜色和产品是多对多的关系。以及一对多的产品和商店/标签。

    $colorId = Color::where('code', $request->color)->get()->first()->id;
    $shopId = $shop->id;
    
    $products = Product::whereHas('colors', function ($query) use ($colorId) {
                    $query->where('id', $colorId); //id or color_id
                })->where('shop_id', $shopId)->get();
    

    【讨论】:

    • 我只想比较两个集合
    • “比较”是什么意思?显示在一个集合中但不在第二个集合中的项目?或者您只想要两个集合中的项目?
    • 如果您只想要两个集合中的项目,那么我的回答是正确的。这将选择所有在请求中设置颜色 ($request->color) 并具有 shop_id $shop->id 的产品。
    • 你可以使用 whereHas $query->where('colors.code', $request->color)
    【解决方案2】:
    intersect()
    

    intersect 方法从原始集合中删除所有值 不存在于给定数组或集合中。所结果的 集合将保留原始集合的键:

    我是用这个方法做到的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2010-10-14
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多