如何在Laravel查询生成器中执行TRIM()和CONCAT()?

时间:2019-03-23 22:59:03

标签: laravel laravel-query-builder

我尝试将FirstName,middlename,Lastname与RAW结合使用查询生成器,但失败了。我的方式错了吗?谢谢

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

4 个答案:

答案 0 :(得分:2)

为什么不使用Laravel模型来实现这一目标?

class Student extends Model {

     protected $appends = 'full_name';

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

然后,Student::get()将为每个学生拥有full_name属性。

答案 1 :(得分:0)

+符号应为逗号:

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

答案 2 :(得分:0)

尝试一下:

public int UserId {get; set;} = 0;

答案 3 :(得分:0)

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

TRIM 功能-从字符串See examples and how to use it

中删除开头和结尾的空格

CONCAT 功能-使用逗号将几个字符串添加在一起:See examples and how to use it

希望会为您提供帮助:)