laravel 查询中具有 where 条件的数组值

array values with where condition in laravel query

我有一个名为 assetIDs 的数组,如下所示

$assetIDs = Collection {#505 ▼
  #items: array:2 [▼
    0 => 4
    1 => 7
  ]
}

我在 table 中有数据,如下所示

并且我正在使用此

对上述 table 进行查询

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)->pluck('supplier_id');

上述查询的结果如下

Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
    2 => 2
  ]
}

这里 whereIn 返回所有满足条件的可能行。实际上我需要得到这样的结果 supplier_id 有两个值 assetIDs array.In 我的 table supplier_id=1 有两个值 47 就像下面 collection.

Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
  ]
}

任何人都可以建议我解决这个问题吗?

你可以试试:

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)
               ->groupBy('supplier_id')
               ->havingRaw('count(distinct asset_id) = ' . count($assetIDs))
               ->pluck('supplier_id');

这是您应该做的 mysql :

1- 获取所有大于1的id supplier_id :

SELECT supplier_id, Count(distinct asset_id) as dist_asst
 FROM Table
 GROUP BY supplier_id
 HAVING dist_asst > 1

2- 然后进行连接:

SELECT t1.supplier_id
FROM Table t1
INNER JOIN (SELECT supplier_id, Count(distinct asset_id) as dist_asst
     FROM Table
     GROUP BY supplier_id
     HAVING dist_asst > 1) t2 on t2.supplier_id = t1.supplier_id