duangang4940 2016-02-28 03:27
浏览 240
已采纳

Laravel嵌套关系foreach循环

I have this relationship betwen item and episode

item:

public function episodes()
    {
        return $this->hasMany(episode::class);
    }

episodes:

public function item()
        {
            return $this->belongsTo(item::class);
        }

In controller

$latestanimes = DB::table('episodes')->where('category', 'anime')
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

What I'm trying to do is get the title of the anime it belongs to of each episode

                       @foreach($latestanimes as $episode)
                              <tr>
                                <td>
                                    @foreach($episode->item as $parrent)
                                      {{  $parrent->title; }}
                                    @endforeach
                                </td>
                                <td>{{ $episode->number }}</td>
                                <td>{{ $episode->category }}</td>
                            </tr>
                        @endforeach

This gives me "Undefined property: stdClass::$item"

I tried debugging in routes.php

Route::get('/dd/{id}', function($id){

        $episode=App\episode::find($id);
        echo $episode->name. '<hr>';

        $item=$episode->item;
        echo $item->title;

    });

And this works ... Is there a way to access it directly? like

{{ $episode->item->title }}

Thanks in advance

  • 写回答

2条回答 默认 最新

  • douba05167 2016-02-28 03:52
    关注

    Fixed it. I was using query builder directly with DB which is not eloquent.

      $latestanimes = episode::with('item')  //eager loading, thanks lagbox
                ->where('category', 'anime')
                ->orderBy('created_at', 'desc')
                ->take(5)
                ->get();
    

    and I can access it directly how I wanted in the first place

    {{$episode->item->title}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建