简体   繁体   中英

Laravel MS SQL DB::RAW Query returns “Invalid column name”

I'm using SQL Server within my Laravel application. I need to group/sum a table for the month/year. My query looks like this:

$positions = BelegPos::select(
    DB::raw("YEAR(Datum) as year"),
    DB::raw("MONTH(Datum) as month"),
    DB::raw("SUM(Menge) as stunden")
)->groupBy("year", "month")
    ->get();

I'll get the following error message:

SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'year'.

I don't know what's wrong, as the query the way I build it works fine with MySQL servers.

Thanks for any hint in the right direction.

UPDATE

I researched a bit more and read about somthing that points out, that the Select Statement isn't available in the GROUP BY section and that you have to add the same query there. so my query looks now like this:

$positions = selectlineBelegPos::select(
                                        DB::raw("YEAR(Datum) as the_year"),
                                        DB::raw("MONTH(Datum) as the_month"),
                                        DB::raw("SUM(Menge) as stunden")
                                        )
                                        ->groupBy(DB::raw("YEAR(Datum) as the_year"),DB::raw("MONTH(Datum) as the_month"))
                                        ->get();

Still not the solution but the error message has changed to this:

SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword (SQL: select YEAR(Datum) as the_year, MONTH(Datum) as the_month, SUM(Menge) as stunden from [BELEGP]

So I think there is just one small thing wrong but can't figure out what.

Any ideas?

Solution

Just found the the solution:

$positions = selectlineBelegPos::select(
                                       DB::raw("YEAR(Datum) AS year"),
                                       DB::raw("MONTH(Datum) AS month"),
                                       DB::raw("SUM(Menge) AS stunden")
                                       )
                                       ->groupBy(DB::raw("YEAR([Datum])"),DB::raw("MONTH([Datum])"))
                                       ->get();

Indeed isn't the dynamically value names (year and month) unavailable in the GROUPBY clause, instead you have to call the DB::raw again but now without generating the key words again.

thank you all for the support!

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