Has*_*ahn 3 php laravel eloquent laravel-collection
我想获取学生的全名,但在我的数据库中,我有两个不同的列:first_name并且last_name.我想同时获取这两列。
控制器
public function getStudentName($id)
{
$students = DB::table("students")->where("students_class_id", $id)
->pluck("first_name", "id");
return json_encode($students);
}
Run Code Online (Sandbox Code Playgroud)
在您的雄辩模型中创建自定义访问器,例如:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
Run Code Online (Sandbox Code Playgroud)
然后在查询中使用它,例如:
$students = DB::table("students")->where("students_class_id",$id)->pluck("full_name","id");
Run Code Online (Sandbox Code Playgroud)
尝试用雄辩的方式来表达:
$students = DB::table("students")->where("students_class_id",$id)->pluck("full_name","id");
Run Code Online (Sandbox Code Playgroud)