2017-05-27 61 views
1

如何將laravel關係結果合併到一個對象中?Laravel - 如何合併關係結果?

MyController.php

public function getUser($id) { 
return TournamentUser::where('customer_id','=', $id)->with('user')->get(); 
    } 

MyModel.php

public function user() { 
return $this->hasOne('App\Models\Customer','customer_id', 'customer_id'); 
    } 

返回結果:

[{ "id":1, "tournament_id":3, "customer_id":2016827550, "point":0, "user":{ "id":1, "customer_id":2016827550, "nickname":"OMahoooo" } }]

預期闕RY返回用戶部分的陣列,但我希望結果是這樣的:

[{ "id":1, "tournament_id":3, "customer_id":2016827550, "point":0, "nickname":"OMahoooo" }]

只獲得綽號部分,而無需用戶陣列。我希望你能理解我。 對不起,我有英語,祝你有個愉快的日子

回答

1

您可以使用map()方法加載數據並手動重新映射。我剛剛測試此代碼,並將其與hasOne()關係完美的作品:

$users = TournamentUser::where('customer_id', $id)->with('user')->get(); 
$users->map(function ($i) { 
    $i->nickname = $i->user->nickname; // Set related nickname. 
    unset($i->user); // Delete user data from the collection. 
    return $i; 
}); 

或者,你可以使用an accessor,但在這種情況下,你會遇到的N+1 problem