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?
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
In Laravel 5, there's now whereColumn
for this, for cleaner code:
Users::whereColumn('username', 'lastname')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With