Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows having 2 columns equal value in laravel Query builder

Tags:

laravel

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?

like image 978
MrezaJafari Avatar asked Sep 20 '14 19:09

MrezaJafari


2 Answers

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

like image 132
Sergiu Paraschiv Avatar answered Nov 05 '22 22:11

Sergiu Paraschiv


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

Users::whereColumn('username', 'lastname')->get();
like image 43
ceejayoz Avatar answered Nov 05 '22 23:11

ceejayoz