Home > Back-end >  SQL query substring in Laravel Eloquent
SQL query substring in Laravel Eloquent

Time:12-14

I am having trouble getting my SQL query right in Laravel 8. What I need is the first character from the column name but only the distinct ones. I want use the chars as links to glossary descriptions.

$chars = DB::table('parts')
            ->distinct()
            ->select('name')
            ->orderBy('name', 'asc')
            ->get();

I tried it by replacing the line from ->select('name') to ->select(DB::raw('SUBSTRING(name, 0, 1)')) line. But the output was obviously wrong. I found an example where SUBSTRING is used exactly like this. What's wrong with my query?

CodePudding user response:

you should change your query like this:

$chars = DB::table('parts')
    ->distinct()
    ->select(DB::raw('SUBSTRING(name, 0,2) char_name'))
    ->orderBy('char_name', 'asc')
    ->get();

CodePudding user response:

Substring in SQL Server and MySQL uses a 1-based index for position. Your second parameter should be 1, to indicate the first character. Your third parameter should be 1, to indicate you only want 1 character.

$chars = DB::table('parts')
    ->distinct()
    ->selectRaw('SUBSTRING(name, 1, 1) name_index')
    ->orderBy('name', 'asc')
    ->get();
  • Related