【问题标题】:Laravel Category, subCategory and PostLaravel 类别、子类别和帖子
【发布时间】:2019-01-17 16:59:06
【问题描述】:

我有 1 个类别和子类别表 table name: categories

另一个表是帖子posts table

当点击谷歌应用脚​​本时,所有关于谷歌应用脚​​本类别和子类别的帖子都会显示enter image description here

我的控制器代码是,控制器名称是 bloglistController

$posts = post::where('category_id', $id)->paginate(7);

但此代码仅显示类别 ID 帖子我想要类别和子类别的帖子

【问题讨论】:

  • 请检查表结构的链接
  • 尝试类似 Category::where(parent_id, 1)->with('post')
  • 不,它没有帮助
  • 我的代码不完整你需要通过laravel热切的laoding
  • 定义类别模型中 parent_id 的 hasMany 关系到发布模型 category_id 字段

标签: php laravel-5 eloquent


【解决方案1】:

对于类别模型

public function post()
{
    return $this->hasMany(Post::class, 'parent_id', 'category_id');
}

在你的控制器中

$category = Category::where('parent_id',1)->first();
$post = $category->post;

【讨论】:

  • 我认为它有效,但我遇到了一些错误。我想要所有的数据,所以我曾经 get();而不是第一个();我这样使用: foreach ($category->post as $new) { echo $new->title; } 但我得到错误属性 [post] 在此集合实例上不存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
相关资源
最近更新 更多