如何将查询转换为Laravel雄辩的ORM

时间:2019-12-09 05:48:26

标签: laravel eloquent

这是我想转换为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

1 个答案:

答案 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();