Skip to content

Feature: Support Union #30

Description

@kassah

This request is to add a feature for SQL Unions.

Laravel Docs: Laravel Eloquent Unions
MySQL Docs: MySQL 8.1 UNION Clause

Union Example

Example SQL input:

(select * from `users` where `last_name` is null) union (select * from `users` where `first_name` is null)

Example Eloquent output:

DB::table('users')
->whereNull('last_name')
->union(
            DB::table('users')
            ->whereNull('first_name')
)
->get();

Union All Example

Example SQL input:

(select * from `users` where `last_name` is null) union all (select * from `users` where `first_name` is null)

Example Eloquent output:

DB::table('users')
->whereNull('last_name')
->unionAll(
            DB::table('users')
            ->whereNull('first_name')
)
->get();

Union with orderBy on id

Example SQL input:

(select * from `users` where `last_name` is null) 
union
(select * from `users` where `first_name` is null) 
order by `id` asc

Example Eloquent output:

DB::table('users')
->whereNull('last_name')
->unionAll(
            DB::table('users')
            ->whereNull('first_name')
)
->orderBy('id')
->get();

Additional Context

While Eloquent doesn't handle returning a UNION from multiple models well (everything will be shoved into the first model's class), it does handle it well as a subselect with multiple models. It makes it much easier to scan across many different models as part of a very complex where.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions