我需要从一列中获取最常用的代码(例如)。我尝试此代码,但这不起作用。
$count = Invoice::with('userinvoicesubaccount')->where('person_id',$id)
->pluck('codeinvoice');
$count = array_count_values($count);
$count = array_keys($count);
$element = $count[0];
首先,我选择所有值的列表。
答案 0 :(得分:0)
// get available 'distinct' codes
$distinct_codes = Invoice::select('codeinvoice')->where('person_id', $id)
->groupBy('codeinvoice')
->pluck('codeinvoice');
// a collection which will hold count of each code against the code
$code_counts = collect();
// for each code get the number of rows
// and add to the collection
foreach ($distinct_codes as $code) {
$code_counts->push(collect([
'code' => $code,
'count' => Invoice::where(
['person_id', $id],
['codeinvoice', $code]
])->count()
]));
}
// get the most used code from that collection
$most_used_code = $code_counts->max->count;
答案 1 :(得分:0)
如果codeinvoice
是发票表的属性,则可以执行以下操作:
$count = Invoice::selectRaw('invoices.codeinvoice, count(invoices.codeinvoice) as ocurrences')
->where('person_id',$id)
->groupBy('codeinvoice');
对于每个返回的行,您将拥有代码以及该代码的出现次数。基于此,如果您只想要最常用的,则可以像这样使用order by
和limit
:
$count = Invoice::selectRaw(invoices.codeinvoice, count(invoices.codeinvoice) as ocurrences')
->where('person_id',$id)
->orderBy('ocurrences', 'desc')
->groupBy('codeinvoice')
->limit(1);
然后,返回的唯一一行将是最常用的代码。
我希望那是你想要的。