Laravel采了,但结合了名字和姓氏进行选择 [英] Laravel pluck but combining first name + last name for select

查看:107
本文介绍了Laravel采了,但结合了名字和姓氏进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将select2与Laravel/Vue项目一起使用,并需要以以下格式返回JSON:

Using select2 with a Laravel / Vue project and need to return JSON in the following format:

[
    { id: 0, text: 'enhancement' },
    { id: 1, text: 'bug' }
]

在Laravel中,我知道我可以使用pluck创建列表数据,例如对于客户:

In Laravel I know I can use pluck to create my list data e.g. for customers:

$customers = Customer::pluck('id', 'first_name');

但是要返回ID和名字+姓氏作为一个单独的名字.

But Want to return the id and first name + last name as a single name.

我该怎么做?

推荐答案

您是否尝试过使用访问器?

Have you tried using Accessors?

https://laravel.com/docs/5.4/eloquent- mutators#defining-an-accessor

我还没有测试过,但这可以工作:

I have not tested it but this could work:

将此添加到您的客户口才模型:

add this to your Customer Eloquent Model:

    public function getFullNameAttribute($value)
    {
       return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
    }

然后尝试:

更新访问者只能在集合上使用.如果尝试Customer::pluck('id', 'full_name'),它将不起作用,因为没有名为full_name的数据库列,因此必须使用Customer::all()->pluck('id', 'full_name')

UPDATED pluck on accessor will only work on a collection. If you try Customer::pluck('id', 'full_name') it will not work since there is no db column named full_name, therefore you must use Customer::all()->pluck('id', 'full_name')

$customers = Customer::all()->pluck('id', 'full_name');

  • 请注意,为了提高性能,最好执行Customer::all(['id', 'first_name', 'last_name'])->pluck(...),这样我们就不会从数据库中提取不必要的列.
    • as a side note, for performance it is probably better to do Customer::all(['id', 'first_name', 'last_name'])->pluck(...) so that we don't pull unnecessary columns from the db.
    • 希望这会有所帮助.

      这篇关于Laravel采了,但结合了名字和姓氏进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆