How to perform TRIM() and CONCAT() in Laravel Query Builder?

倖福魔咒の 提交于 2019-11-28 11:41:00

问题


I tried to take FirstName, middlename, Lastname used the Query Builder in combination with RAW but failed. is my way wrong? Thanks

$student = \DB::table('student')
                        ->select(DB::raw('RTRIM(LTRIM(CONCAT(
                                          COALESCE(FirstName +  ''),
                                        COALESCE(MiddleName +  ''),
                                        COALESCE(Lastname, ''))))
                                        AS Name'))
                        ->get();

回答1:


$student = DB::table('student')
    ->select(
        DB::raw("TRIM(CONCAT(FirstName,' ',MiddleName,' ',LastName)) AS Name")
    )->get();

TRIM Function - Remove leading and trailing spaces from a string See examples and how to use it

CONCAT Function - Add several strings together using comma: See examples and how to use it

Hope will help you :)




回答2:


Why not using Laravel model way of achiving this?

class Student extends Model {

     protected $appends = 'full_name';

     public function getFullNameAttribute() {
         return $this->FirstName . ' ' . $this->MiddleName . ' ' . $this->LastName; 
     }
}

Then, Student::get() will have full_name attribute for each student.




回答3:


The + symbols should be a comma:

$student = \DB::table('student')
    ->selectRaw("TRIM(CONCAT(COALESCE(FirstName,  ''), COALESCE(MiddleName,  ''), COALESCE(Lastname, ''))) AS Name")
    ->get();



回答4:


Try this :

$student = \DB::table('student')
               ->select(\DB::raw('CONCAT_WS(" ", `FirstName`, `MiddleName`, `Lastname`) as Name'))
               ->get();


来源:https://stackoverflow.com/questions/55319163/how-to-perform-trim-and-concat-in-laravel-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!