【问题标题】:Laravel nested relationship foreach loopsLaravel 嵌套关系 foreach 循环
【发布时间】:2016-06-11 05:46:43
【问题描述】:

我在项目和情节之间有这种关系

项目:

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

剧集:

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

在控制器中

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

我要做的是获取每集所属动漫的标题

                       @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

这给了我“未定义的属性:stdClass::$item”

我尝试在 routes.php 中调试

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

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

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

    });

这行得通... 有没有办法直接访问它?喜欢

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

谢谢提前

【问题讨论】:

    标签: php laravel laravel-5 nested relationship


    【解决方案1】:

    修复它。我直接用DB 使用查询生成器,这不是很有说服力。

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

    我一开始就可以按照自己的意愿直接访问它

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

    【讨论】:

      【解决方案2】:

      你的代码中的一些问题是你正在编写的剧集模型 belongsTo 这意味着剧集只有一个导致 foreach 循环不起作用的项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-17
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        相关资源
        最近更新 更多