OMahoooo
OMahoooo

Reputation: 427

Laravel - How to merge relationship results?

how can i merge laravel relationship results in to one object?

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');
    }

returning result :

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

as expected query returns user section as array but i expect result like this :

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

only get nickname section without user array. I hope you understand me. Sorry for my english , have a nice day

Upvotes: 1

Views: 1139

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You can load the data and remap it manually using map() method. I've just tested this code and it works perfectly with hasOne() relationship:

$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;
});

Alternatively, you could use an accessor, but in this case, you'll meet the N+1 problem.

Upvotes: 1

Related Questions