简体   繁体   中英

Laravel groupBy on particular column

I'm running a Laravel 8 project on PHP 7.4. I have a table called add_ons and a model called Addon . A Addon model has a column called group , which is how I'd like to group certain rows together under one object, when I try to use the groupBy method on my model I get this error:

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'domainmonitor_db.add_ons.id' which is not functionally dependent on columns in GROUP BY clause

What am I missing to achieve the grouped functionality I desire?

/**
 * Handle the incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function __invoke(Request $request)
{
    $addons = Addon::groupBy('group')->get();
}

在此处输入图像描述

Some database systems -- PostgreSQL in particular -- require that all columns SELECT -ed in a query with a GROUP BY be aggregate columns.

The reason for this is data correctness; say you had multiple rows with a different value in a column that WASN'T the "group by" column (eg SELECT group_id, name from items GROUP BY group_id ) -- what should the DBMS say is the value of the column in the squashed row? It cannot know that, and the DBMS shouldn't guess. Furthermore, by guessing what should go in that column instead of enforcing this, MySQL gives back garbage data for queries with a group clause.

When you use a bare [Model]::groupBy() it's querying all columns (ie a SELECT * FROM... ) many of which may not be aggregated columns.

You state you want a single object for the grouped records, but there are some unanswered questions:

  • What columns should there be?
  • If, say, stripe_id is part of the object, which row should it come from?

What you may find useful instead is the Illuminate\Support\Collection interface's groupBy() method, which merely organizes the objects by a common column, and doesn't squash any data:

$collection = Addons::query()->get();
$grouped_collection = $collection->groupBy('group');

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