这是我想转换为Laravel雄辩的ORM的SQL查询。
SELECT v.product_id
FROM (
SELECT product_id, count(*) AS matches
FROM product where filter_id IN (2,4)
GROUP BY product_id
) AS v
WHERE v.matches = 2
这是我尝试的代码。它返回所有包含2或4的filter_id
。我想获取具有product_id
2 和 4。
filter_id
$filter = [2, 4];
$products =
OcProductFilter::with('product')
->whereHas('product', function ($query) use ($filter) {
$query->whereIn('oc_product_filter.filter_id', array($filter));
})->get();
这是OcProductFilter
的模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OcProductFilter extends Model
{
public $timestamps = false;
protected $primaryKey = 'product_id';
protected $table = 'oc_product_filter';
protected $fillable = ["filter_id", 'product_id'];
protected $hidden = [];
public function product()
{
return $this->belongsTo('App\OcProduct', 'product_id', 'product_id');
}
}
这是product_filter表 table image
答案 0 :(得分:1)
我将使用以下原始MySQL查询,该查询不需要任何子查询:
SELECT product_id, COUNT(*) AS matches
FROM product
WHERE filter_id IN (2, 4)
GROUP BY product_id
HAVING matches = 2;
您更新的Laravel /口才代码:
OcProductFilter::with('product')
->select('product_id', DB::raw('COUNT(*) matches'))
->groupBy('product_id')
->whereIn('filter_id', [2, 4])
->havingRaw('matches = ?', [2])
->get();