doumibi6899 2016-12-13 18:34
浏览 36
已采纳

如何在laravel中处理多级别的一对多关系

I have three models in my laravel 5.3 application with relationships as follow

Category:

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


Subcategory:

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

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


Post:

public function subcategory(){
    return $this->belongsTo('App\Subcategory');
}

Now in my controller I only have a category and I want all the posts (ordered by id) that are in the subcategories which belong to the category I have. Something like:

$posts = $category->subcategories->posts;

But I don't know how to do that. Help will be appreciated.

  • 写回答

1条回答 默认 最新

  • dppx9253 2016-12-13 18:38
    关注

    Hey Ahmed

    What you need is the use of the hasManyThrough relation:

    Category:
    
    public function posts(){
        return $this->hasManyThrough('App\Posts', 'App\Subcategory');
    }
    

    Then you can use it like this:

    $posts = $category->posts;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题