【问题标题】:belongsToMany and belongsTo属于ToMany 和属于To
【发布时间】:2018-07-17 19:54:30
【问题描述】:

我在控制器中创建了这个查询:

  $query = tag_performers::with('performers')->where('slug', '=', 'someting')->get();

  return view('frontend.newperformer')->with('hello', $query)
                                      ->with('sectionTitle', 'Performers');

我在Tinker 中对其进行了测试,它可以工作。所以我想在我的视图文件中使用它

@foreach($hello->performer as $h)
  {{ $h->performers->id }}
@endforeach

我有错误

“此集合实例上不存在属性 [performers]。(...)”

我不知道为什么。谁能帮帮我?

【问题讨论】:

  • 请显示dd($query);performers关系的结果。
  • 表演者与表演者。检查您正在使用的多个变量

标签: laravel many-to-many relationship


【解决方案1】:

使用

@foreach($hello->performer as $h)
   {{ $h->id }}
@endforeach

【讨论】:

    【解决方案2】:

    我假设查询返回了一些数据:

    $query = tag_performers::with('performers')->where('slug', '=', 'someting')->get();
    

    通过查询,tag_performers 似乎有很多 performers,反之亦然,因此您需要迭代两次。

      @foreach($hello->performers as $performers)
         @foreach($performers as $performer)
             {{$performer->id}}
         @endforeach
      @endforeach
    

    但是帖子的标题是belongs to many and belongs to,所以问题是您正在访问关系,然后尝试再次访问该关系,这没有意义,所以它应该是:

      @foreach($hello->performer as $h)
        {{ $h->id }}
      @endforeach
    

    【讨论】:

    • 它不起作用。我之前尝试过你的第二个代码(我在帖子中犯了错误)但它不起作用
    【解决方案3】:

    我认为问题可能是您正在使用的多个变量

    表演者与表演者s

    $query = tag_performers::with('performers')->where('slug', '=', 'someting')->get();
    
      return view('frontend.newperformer')->with('hello', $query)
                                          ->with('sectionTitle', 'Performers');
    
    
    
    @foreach($hello->performers as $h) /* <-- notice the s  */
      {{ $h->performers->id }}
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 2017-10-27
      • 1970-01-01
      • 2020-08-10
      • 2015-01-10
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多