【问题标题】:Many-to-many relationship - it doesn't display elements多对多关系 - 它不显示元素
【发布时间】:2019-04-22 23:37:26
【问题描述】:

我想要多对多的关系。所以我创建了: 进入游戏模型

public function category(){
      return $this->belongsToMany('App\Category');
  }

进入类别模型

public function games(){
          return $this->hasMany('App\Game');
    }

进入控制器

$category = Category::where('slug', $slug)->first();
      dd($category->games());
      return view('frontend.game.gamelist')->with('elements', $category->games());

一般来说,我会尝试显示所有属于特定类别的游戏。我看到这样的东西

如果我删除 dd() 视图将不会显示任何元素。但视图没有问题。

@foreach($elements as $element)
//...
@endforeach

为什么它不起作用?

【问题讨论】:

  • 必须是$category->games 而不是$category->games(),像属性一样调用。

标签: laravel many-to-many relationship


【解决方案1】:

您的Category 模型还需要在其games() 关系中具有belongsToMany

public function games() {
    return $this->belongsToMany('App\Game');
}

【讨论】:

    【解决方案2】:

    您正在使用延迟加载的数据

    Laravel eloquent Lazy Vs. Eager Loaded

    更新您的控制器方法:

    $category = Category::with('games')->where('slug', $slug)->first();
    dd($category->games);
    
    return view('frontend.game.gamelist')->with('elements', $category);
    

    您必须获取所有游戏类别,以便您可以通过查询获取这些数据,也可以在dd 函数中查看它们。

    如果您只获取类别然后执行category->games(),它将在您的视图中执行另一个查询。

    【讨论】:

      【解决方案3】:

      当你这样做时:

      $category->games();
      

      您正在访问关系本身(用于附加约束),而不是关系的元素。详情请查看this other answer

      试试这个:

      $category->games;
      

      OBS

      在进行多对多关系时,需要在两个模型中指定belongsToMany 方法。

      Category.php

      public function games()
      {
            return $this->belongsToMany('App\Game');
      }
      

      【讨论】:

        【解决方案4】:

        您的Category 模型中还需要有一个belongsToMany 关系才能建立多对多关系。您可以通过以下方式实现:

        public function games() 
        {
            return $this->belongsToMany('App\Game');
        }
        

        然后在您的类别控制器中,您有:

        $category = Category::with('games')->where('slug', $slug)->get();
        
        return view('frontend.game.gamelist', compact('category');
        

        那么在你看来,你可以通过

        来访问游戏列表
        @foreach($category->games as $game)
        //...
        @endforeach
        

        【讨论】:

          猜你喜欢
          • 2016-07-16
          • 1970-01-01
          • 1970-01-01
          • 2014-03-29
          • 2013-05-06
          • 2012-04-24
          • 1970-01-01
          • 2021-11-13
          • 1970-01-01
          相关资源
          最近更新 更多