您是否尝试过使用访问器?
https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
我还没有测试过,但这可以工作:
将此添加到您的 Customer Eloquent 模型中:
public function getFullNameAttribute()
{
return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}
然后尝试:
UPDATED pluck on accessor 仅适用于集合。如果您尝试Customer::pluck('id', 'full_name'),它将无法正常工作,因为没有名为 full_name 的 db 列,因此您必须使用Customer::all()->pluck('full_name', 'id')
$customers = Customer::all()->pluck('full_name', 'id');
- 附带说明,为了提高性能,最好使用
Customer::all(['id', 'first_name', 'last_name'])->pluck(...),这样我们就不会从数据库中提取不必要的列。
希望这会有所帮助。
更新日期:- 2021 年 8 月 26 日
如果我们使用计算属性accessor functionality,那么请注意一件重要的事情......
Laravel 访问器功能在从数据库中获取数据之后起作用。所以我们必须在Query结束时声明"pluck(accessorName)"....
例如:-
错误的方法:-
$data = Model::pluck('full_name','id)->get();
$data = Model::pluck('full_name','id)->all();
在上述两个查询中,如果 DataTable 中没有 full_name 字段,则会出现 Unknown column error
正确的方法:-
$data = Model::get()->pluck('full_name','id');
$data = Model::all()->pluck('full_name','id');
在上述两个查询中,即使您在 DataTable 中没有 full_name 字段,它也能完美运行