如何在 Laravel Query Builder 中执行 TRIM() 和 CONCAT()?

How to perform TRIM() and CONCAT() in 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();

为什么不使用 Laravel 模型方法来实现这一点?

class Student extends Model {

     protected $appends = 'full_name';

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

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

+ 符号应该是逗号:

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

试试这个:

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

希望对你有所帮助:)