是否可以使用eloquent从单个列中仅选择重复值?

时间:2015-03-29 10:28:46

标签: php sql laravel laravel-4 eloquent

id|p.id|product

1 |8   |chair
2 |8   |table
3 |2   |chair
4 |4   |guitar
5 |8   |glasses

我想选择p.id 8和p.id 2产品但是我想要重复的值(椅子)。这与截然不同。到目前为止我已经

$product =modelname::whereIn('p.id', array(8,2))->select('product')->get();

这显然选择了2个p.id,但我并不知道如何在使用eloquent时使用聚合函数,例如count。任何帮助深表感谢。 (我使用laravel 4.2 btw)

2 个答案:

答案 0 :(得分:2)

如果您使用以下内容将p.id重命名为p_id

$product= modelname::selectRaw('product, count(product) AS aggregate')->whereIn('p_id', array(8,2))->groupBy('product')->having('aggregate','>',1)->get();

你会得到结果:

array:1 [▼
  0 => {#121 ▼
    +"product": "chair"
    +"aggregate": 2
  }
]

答案 1 :(得分:0)

如果要选择p.id 8和p.id 2的值,可以使用如

之类的代码
$product = Modelname::whereIn('p.id', array(8,2))->get();

现在$product变量以数组格式联系值。现在您可以传递变量进行查看,或者如果您希望计数使用count($product)