【问题标题】:Laravel - How to merge relationship results?Laravel - 如何合并关系结果?
【发布时间】:2017-05-27 07:35:47
【问题描述】:

如何将 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" } }]

正如预期的那样,查询将用户部分作为数组返回,但我希望得到这样的结果:

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

只获取没有用户数组的昵称部分。我希望你能理解我。 对不起我的英语,祝你有愉快的一天

【问题讨论】:

    标签: laravel


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多