ホーム > Laravel > Laravel Union throws an error unless the number of columns matches the original table
Laravel

Laravel Union throws an error unless the number of columns matches the original table

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents of Laravel articles

I wrote an article on how Laravel Union throws an error unless the number of columns matches the original table.

What kind of error occurs

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select `title`, `created_at` from `posts` where `title` is not null) union (select `title` from `items`))

You will get this error.

How to resolve

The error message says, "The used SELECT statements have a different number of columns."

Therefore, I think this error can be resolved by selecting the same number of columns.

  use App\Models\Item;
  use App\Models\Post;

~~~
public function index()
{
  $items = Item::select('title','created_at');
  $results = Post::select('title','created_at')
      ->union($items)
      ->get();
  dd($results);
}

Summary

That's it.

I wrote an article about the error that occurred when using Union in Laravel.

I hope this can be helpful to someone.

For feedback or complaints, please contact me via Twitter DM.

That's all!

Popular Articles

Deploying a PHP7.4 + Laravel6 project to AWS EC2

Implementing breadcrumbs in Laravel with laravel-breadcrumbs

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!