Howard
Howard

Reputation: 3758

How can I write this MySQL using Laravel Query builder?

I have the following MySQL query and I would like to change it to the correct format for Laravel's Query builder.

SELECT DISTINCT(colors) FROM `cards` ORDER BY LENGTH(colors) DESC

This is what I currently have:

table('cards')
    ->orderBy(LENGTH(colors), 'desc')
    ->get();

Upvotes: 0

Views: 271

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

Note that you have to use raw methods to be able to run SQL functions like LENGTH().
This should work:

DB::table('cards')
    ->select('colors')
    ->distinct()
    ->orderByRaw('LENGTH(colors) DESC')
    ->get();

Upvotes: 2

Related Questions