【问题标题】:Property [title] does not exist on this collection instance hasMany relationship此集合实例上不存在属性 [title] hasMany 关系
【发布时间】:2018-08-05 18:51:38
【问题描述】:

我有以下两个模型Page.php和PageCategory.php`,关系如下: Page.php

public function category() 
{
    return $this->belongsTo('App\PageCategory','category_id', 'id');
}

PageCategory.php

public function page() 
{
    return $this->hasMany('App\Page','id');
}

以下是上述模型的db表结构:

页数

id | title | content | category_id

page_categories

id | name

我正在尝试将所有类别名称打印为主菜单项,并将属于其类别的页面名称打印为导航栏中的子菜单项。在控制器中使用以下代码:

$pcategories = PageCategory::all();

在视图中:

@foreach($pcategories as $category)
<div class="dropdown-menu">
  <ul>
    <li>
     <a href="#">{{ $category->page->title }}</a>
    </li>
  </ul>
</div>
@endforeach

使用上面的代码,我遇到错误消息此集合实例上不存在属性 [title],如果有人能指出我所犯的错误,我将不胜感激。

【问题讨论】:

    标签: php laravel eloquent laravel-5.5


    【解决方案1】:

    一个集合可以包含多个记录 - 通过执行$category-&gt;page,您将获得一个页面集合。

    你应该像这样循环遍历集合;

    @foreach($pcategories as $category)
    <div class="dropdown-menu">
      <ul>
        @foreach($category->page as $page)
        <li>
         <a href="#">{{ $page->title }}</a>
        </li>
        @endforeach
      </ul>
    </div>
    @endforeach
    

    【讨论】:

    • 谢谢。我查看了文档,发现是一样的。
    猜你喜欢
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2018-07-14
    • 1970-01-01
    • 2020-11-12
    • 2019-03-23
    相关资源
    最近更新 更多