I’m making a request to retrieve data from two tables. The number of columns is the same. But for some reason, an error occurs that says that the select has a different number of columns. And when you make a query for one table, everything is fine.
$asks = DB::table('asks')
->select('id', 'user_id', 'text', 'price', 'ask_id', 'created_at')
->where('user_id', 125)
->union(DB::table('my_requests')
->select('id', 'user_id', 'text', 'price', 'ask_id', 'created_at')
->where('user_id', 125))
->paginate(10);
When I fix on get everything is fine but paginate doesn’t work
2
Answers
Make sure that you are following these 2 conditions:
First, the number and the orders of columns that appear in all SELECT statements must be the same. This seems to be correct in your code.
Second, the data types of columns must be the same or compatible.
Are the data types the same? Check that all things related to the tables are the same.
You may want to export the database, then check that the structure is the same exactly for both tables and fields.
Also try the code directly like this to see if it is something in the framework code you are using.
This allows you to see if the error is in the database or the code.
If the above query works directly in phpmyadmin sql query editor or equivalent program.
There is Laravel issue for version <= 5.7, when
paginate
don’t work withunion
, see here: https://github.com/laravel/framework/issues/21958You need to use custom paginator (load all results and paginate it after, or some library like https://github.com/krossroad/laravel-unionpaginator), or update your dependencies versions