Schulz Martin
Schulz Martin

Reputation: 41

Laravel query with where and where

I've trying to basically do two SQL requests into one laravel array.

These are my SQL

SELECT * FROM `transactions` WHERE `plan` LIKE '1050' ORDER BY `updated_at` DESC
SELECT * FROM `transactions` WHERE `user` LIKE '1050' ORDER BY `updated_at` DESC

I want to have all transaction that have "plan" == "1050" AND all transactions that have "user" == "1050" in one variable.

This is not working for me:

$ct=transactions::where('user',$user->id)
    ->orWhere('plan', $user->id)
    ->orderby('created_at',"asc")->get();

Upvotes: 2

Views: 52

Answers (1)

apokryfos
apokryfos

Reputation: 40653

The context agnostic way to combine the results of two union compatible queries (such as yours) would be:

$result = transactions::where('plan', 'LIKE', $user->id)->orderBy('updated_at', 'DESC')
                 ->union(
                      transactions::where('user', 'LIKE', $user->id)
                         ->orderBy('updated_at', 'DESC')
                 )
                 ->get();

This of course means that the results are ordered by plan then user. You can sort them by updated_at globally using the below function on the result:

$result = $result->sortBy('updated_at', 'DESC');

There's also a way to do it on the query level but I don't see much benefit since you're getting all the data anyway.

The above query should be functionally equivalent to:

$result = transactions::orWhere('plan', 'LIKE', $user->id)
                        ->orWhere('user', 'LIKE', $user->id)
                        ->orderBy('updated_at', 'DESC')
                        ->get();

This will have the same results but in a different order than the union.

Upvotes: 1

Related Questions