0

在控制器中,我创建了一个集合:

$playershome = App\Team::where('id', $session->team1_id)->with('players')->first();

并调用我的观点:

        return view('member.home', compact('user', 'session', 'playershome', 'playersaway'));

在我的团队模型中,我有:

    public function players(){
        return $this->belongsToMany(User::class, 'team_users');
}

集合被创建:

团队合集

但我不知道如何在我的视图中检索“玩家”项目。我尝试:

@foreach($playershome->players as $player)

但我得到了:

Invalid argument supplied for foreach()

怎么了?

更新视图:

                                            <div class="mt-body">
                                            <h3 class="mt-body-title"> {{$session->team1Id->name}} </h3>
                                            <p class="mt-body-description"> It is a long established fact that a reader will be distracted </p>
                                            <ul class="mt-body-stats">
                                                @foreach($playershome->players as $player)

                                                    <li class="font-green">
                                                        <img src="/storage/{{$player->avatar}}"></li>
                                                @endforeach
                                            </ul>
                                            <div class="mt-body-actions">
                                                <div class="btn-group btn-group btn-group-justified">
                                                    <a href="javascript:;" class="btn">
                                                        <i class="icon-bubbles"></i> Punti </a>
                                                    <a href="javascript:;" class="btn ">
                                                        <i class="icon-social-twitter"></i> K/D </a>
                                                </div>
                                            </div>
                                        </div>
4

2 回答 2

1

查看您在评论中的聊天,我发现您players在您的团队表中使用了相同的名称来调用一个属性,并且还调用了与用户的关系players。尝试将关系重命名为其他内容,在查询和 foreach 中更改它。

编辑:发现与您相同的问题的stackoverflow问题:Laravel get Eloquent relationship by same name as its attribute

于 2017-07-04T08:55:35.450 回答
0

试试这个方法

$playershome = App\Team::with('players')->where('id', $session->team1_id)->get();
于 2017-07-03T18:50:28.513 回答