MrezaJafari
MrezaJafari

Reputation: 108

Select rows having 2 columns equal value in laravel Query builder

I want to write a query which selects rows where 2 attributes from 1 entity have equal value.

This would be an example of doing this in raw SQL:

Select * from users u where u.username = u.lastname

Does laravel have any methods that take 2 column names as parameters and return the matching results?

Upvotes: 5

Views: 12521

Answers (2)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

What you need is a DB::raw expression:

DB::table('users')
    ->where('username', '=', DB::raw('lastname'))
    ->get();

The only thing DB::raw actually does is to tell the query interpreter not to treat 'lastname' like any other string value but just interpolate it in the SQL as it is.

http://laravel.com/docs/queries#raw-expressions

Upvotes: 34

ceejayoz
ceejayoz

Reputation: 180004

In Laravel 5, there's now whereColumn for this, for cleaner code:

Users::whereColumn('username', 'lastname')->get();

Upvotes: 8

Related Questions