问题
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