我想在 API 中自定义 hasMany() 的输出

I want customize Output from hasMany() in my API

我只是尝试更改 Api 中的输出 json 代码,但我不明白它是如何工作的。

我尝试 2 table 之间的关系。第一个 table 是 user 第二个 table 是 LogTransfer.

我正在使用 Lumen (5.7.7)(Laravel 组件 5.7.*)

我有两个 table 处于关系状态。

我的第一个 table user 有列 [user_id, username]user_id 引用列 id_sourceid_destination 第二个 table.我想 change/fill id_sourceid_destination 到我从第一个 table 获得的 用户名 - 我该怎么做?

我将它作为 json 返回给 api,它的输出是

"id_transfer": 1,
        "id_source": 3,
        "id_destination": 1,
        "jumlah": 1000,
        "waktu": "2019-01-22 04:13:00",
        "qrLog": 1,
        "jenis": "Pembelian"

我希望我的输出变成这样

"id_transfer": 1,
        "source": admin,
        "destination": iko,
        "jumlah": 1000,
        "waktu": "2019-01-22 04:13:00",
        "qrLog": 1,
        "jenis": "Pembelian"

我的代码在用户模型中

public function logTransferFrom()
{
    return $this->hasMany('App\LogTransfer','id_destination');
}

我的代码在控制器中

public function from(Request $request) 
{    
    $logTransfer = Auth::user()->logTransferFrom()->get();

    return response()->json(['status' => 'success','result' => $logTransfer]);
}

开箱即用不支持此类功能,因为所有映射都是通过 ids.But 完成的,您可以使用 accessors and appends

实现类似的功能

在您的日志模型中添加此

public $appends = ['source', 'destination']; //dyn. appends keys to json

public function userSource()                     // mapping helper for source
{
    return $this->belongsTo('App\User', 'id_source');
}

public function userDestination()                // mapping helper for destination
{
    return $this->belongsTo('App\User', 'id_destination');
}

public function getSourceAttribute($value)       // gets the username for id_source
{
    return $this->userSource->username;
}

public function getDestinationAttribute($value)  // gets the username for id_destination
{
    return $this->userDestination->username;
}

就是这样!

现在,当您转储 json 时,除了之前的那些之外,它应该还有两个键,"source" 和 "destination",其值作为来自用户 [=24= 的匹配用户名].