Categories
Learning

If its Laravel or a simple MYSQL a query/fetch of inner join table, return’s id of joined table, but you don’t want that, how to fix?

Hello,

First sorry for such long question in the heading. Will start with small story and then right to the solution fix I found.

Facing issue of getting id of Joined table in my current laravel project, where I need a Id column value from the Main table not the one which I used to inner join for the records to pull in.

Here is my existing query of Laravel returning t he id of customer table where I was looking id of Bill’s Table:

$data = Bill::join('customers', 'customers.id', '=', 'bills.customer_id')
                ->where('bills.store_id', 'LIKE', '%'. $storeId . '%')
                ->orderBy('bills.id', 'desc')
                ->get(['bills.*','customers.*', ]);

So the right solution is at the last line in the above code, please carefully see the get() function array parameters; I switched them, so it finally returns the id values of bills not of customer table. (as customer table also id column which matches with bill’s table column)

$data = Bill::join('customers', 'customers.id', '=', 'bills.customer_id')
                ->where('bills.store_id', 'LIKE', '%'. $storeId . '%')
                ->orderBy('bills.id', 'desc')
                ->get(['customers.*', 'bills.*']);

This results be the records with bills id not customer’s id in laravel elqouent or mysql inner join.

Thanks for reading and learning.

Happy learning.