Laravel:如何在groupBy查询中显示访问器?

时间:2019-09-03 10:10:30

标签: php laravel eloquent

我在Ticket.php中有一个这样的模型,其中包含一个称为getAssigneeFullNameFormattedAttribute()的增变器。 我将mutator属性附加为assignee_full_name_formatted到模型响应中。这里是模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    protected $appends = ['assignee_full_name_formatted'];
    protected $hidden = ['assignee'];

    /**
     * Get the assignee of the support ticket.
     */
    public function assignee()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * Get the assignee of the ticket formatted.
     *
     * @return null | string
     */
    public function getAssigneeFullNameFormattedAttribute()
    {
        $person = $this->assignee;
        return $this->getShortFullName($person);
    }

    ...

    /**
     *
     * @param  string  $person
     *
     * @return string
     */
    private function getShortFullName($person)
    {
        ...
        return $full_name_formatted;
    }
}

在控制器TicketController.php中,我使用这样的查询从模型的属性(assignee_name)返回唯一值:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Ticket;

class TicketController extends Controller
{
    /**
     * Display a listing of 'assignee_name's.
     *
     * @return \Illuminate\Http\Response
     */
    public function getFieldUniqueRecords(Ticket $tickets, Request $request)
    {
        $unique_records = $tickets->select('assignee_name')
            ->groupBy('assignee_name')
            ->paginate($pagination_results_per_page);
        return $unique_records;
    }
}

但是,输出未在访问者assignee_full_name_formatted中显示该值:

{
    "current_page": 1,
    "data": [
        {
            "assignee_name": "joe@example.com",
            "assignee_full_name_formatted": null,
            ...
        },
        ...
}

如果我该如何确保显示访问器assignee_full_name_formatted中的值而不显示null

谢谢

0 个答案:

没有答案