Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tomasosho's avatar

How to query same column name and id in multiple table

$Query = DB::tables('melanine_finishes','melamine_out_finishes', 'plastic_out_finishes',)
        ->select('item_no', 'id', DB::raw('SUM(qty) AS qty'),)
        ->groupBy('item_no', 'id')
        ->orderBy('created_at','desc')->paginate(5);
0 likes
3 replies
Snapey's avatar

prefix the column names with the table name, using a period

$Query = DB::tables('melanine_finishes','melamine_out_finishes', 'plastic_out_finishes',)
    ->select('melanine_finishes.item_no', 'melanine_finishes.id', DB::raw('SUM(qty) AS qty'),)
    ->groupBy('item_no', 'id')
    ->orderBy('created_at','desc')->paginate(5);

for example (I don't know which of your tables has item_no). Repeat for all fields

Also, rather than just list the tables, I would recommend explicit joins - or better, use Eloquent.

tomasosho's avatar

I'm getting this

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'melanine_finishes.item_no' in 'field list' (SQL: select `melanine_finishes`.`item_no`, `melanine_finishes`.`id`, SUM(melanine_finishes.qty) AS qty from `melanine_finishes` as `melamine_out_finishes` group by `item_no`, `id` order by `created_at` desc limit 5 offset 0)
Snapey's avatar

You need to adapt my example and choose the correct table for each field, and then repeat for all fields in your query

Please or to participate in this conversation.