简体   繁体   中英

SQL query substring in Laravel Eloquent

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?

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM