代码之家  ›  专栏  ›  技术社区  ›  David Aleixo

Laravel-oneToMany返回未定义的属性

  •  -1
  • David Aleixo  · 技术社区  · 11 年前

    我只是在所有帖子中搜索这个问题,但我无法得到答案。

    我有3个表:用户|类别|部门,具有以下模型:

    用户.php

    public function categorys(){
            return $this->hasMany('Category');
    }
    

    类别.php

    public function user(){
        return $this->belongsTo('User');
    }
    public function sectors(){
        return $this->hasMany('Sector');
    }
    

    扇区.php

    public function category(){
        return $this->belongsTo('Category');
    }
    

    桌子

    • 用户:
      • id,名称
    • 类别:
      • id,name,user_id(fk)
    • 部门:
      • id,name,category_id(fk)

    我想在一个视图中打印经过身份验证的用户的所有扇区,如下所示:

    $user = new User;
    $user = Auth::user(); 
    $sectors = $user->categorys->sectors;
    

    并在视图中的$sectors变量中使用

    @foreach($sectors as $sector)
      {{ $sector->id }}
      {{ $sector->name }}
    @endforeach
    

    但我得到了这个错误:

    Undefined property: Illuminate\Database\Eloquent\Collection::$sectors
    

    需要帮助!谢谢

    BR

    2 回复  |  直到 11 年前
        1
  •  0
  •   Edwin Krause    11 年前

    要么你忘了在文章中提到它,要么 sector_id 中缺少字段 categorys 桌子

    根据您的数据库结构,表中没有外键 分类 到桌子 sectors

        2
  •  0
  •   David Aleixo    11 年前

    正如我之前提到的,这是上述问题的答案。 hasmanythhough关系是关联和轻松查询3个表的正确方式。

    对于模型User.php,您需要创建关系:

    public function sectors(){
        return $this->hasManyThrough('Sector','Category');
    }
    

    现在,在控制器中,您需要执行以下操作:

    $user = new User;
    $user = Auth::user(); 
    $sectors = $user->sectors;
    #return the view showsectors
    return View::make('showsectors')->with('sectors', $sectors);
    

    使用此变量(扇区)打印查询结果( 一个用户的所有扇区描述 )在您看来,具有以下内容:

    @foreach($sectors as $sector)
     {{ $sector->id }}
     {{ $sector->description }}
    @endforeach
    

    感谢您的帮助。

    BR