Grof
Grof

Reputation: 111

Comparing two columns in Laravel 5

I am using Laravel

Let's say, I have two date fields in my table. If I want to compare them, i can do whereRaw clause.

$query->whereRaw('date1 > date2')->get()

Is there a way to make a modification to date2 inside this query, so it is actually date2-1day?

Something like:

$query->whereRaw('date1 > (date2-1day)')->get()

Upvotes: 2

Views: 2242

Answers (2)

Akshay K Nair
Akshay K Nair

Reputation: 1476

Another way would be using whereColumn like

$users = DB::table('users')
             ->whereColumn('updated_at', '>', 'created_at')
             ->get();

OR

UserTable::whereRaw('column1 != column2')->get();

Upvotes: 0

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

You are free to call any SQL code in the "raw" part of your query, so you could do sth like below:

$query->whereRaw('date1 > DATE_SUB(date2, INTERVAL 1 DAY)')->get();

Keep in mind that executing SQL code this way will make your queries work only in databases that support such functions.

Upvotes: 3

Related Questions