在 Laravel/Vue 项目中使用 select2,需要返回以下格式的 JSON:
[
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' }
]
在 Laravel 中,我知道我可以使用 pluck 来创建列表数据,例如对于客户:
$customers = Customer::pluck('id', 'first_name');
但想要将 id 和名字 + 姓氏作为单个名称返回。
我该怎么做?
最佳答案
您尝试过使用访问器吗?
https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
我还没有测试过,但这可以工作:
将其添加到您的客户 Eloquent 模型中:
public function getFullNameAttribute()
{
return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}
然后尝试:
已更新访问器上的 pluck 仅适用于集合。如果您尝试 Customer::pluck('id', 'full_name')
它将不起作用,因为没有名为 full_name 的数据库列,因此您必须使用 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 访问器功能在从数据库获取数据后起作用。所以我们必须在查询末尾声明“pluck(accessorName)”...
例如:-
错误方法:-
$data = Model::pluck('full_name','id)->get();
$data = Model::pluck('full_name','id)->all();
in above two queries if you does not have full_name field in DataTable you will get Unknown column error
正确方法:-
$data = Model::get()->pluck('full_name','id');
$data = Model::all()->pluck('full_name','id');
in above two queries it will works perfectly even if you doesn't have full_name field in DataTable
关于Laravel Pluck 但结合名字+姓氏进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44475537/