简体   繁体   中英

Is it possible to select only repeated values from a single column using eloquent?

Table

id|p.id|product

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

I would like to select p.id 8 and p.id 2 products however II want the repeated values (chair). This is the opposite of distinct. So far I have

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

This obviously selects the 2 p.id's however I'm unaware of how to use aggregate functions such as count when using eloquent. Any help is much appreciated. (I use laravel 4.2 btw)

If you rename your p.id into p_id using:

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

you will get as result:

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

If you want to select value of p.id 8 and p.id 2 you can use the code like

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

Now the $product variable contact the value in array format. now you can pass the variable to view or if you want the count use count($product)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM