繁体   English   中英

Laravel 3张桌子之间的关系

[英]Laravel Relationship between 3 tables

所以我想获取类别名称,这就是我的平板电脑:

类别 :ID,名称

post_categories :id,post_id,category_id

发布 :ID,列

我有以下模型: PostPostCategoryCategory

职位模型:

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

后类别模型:

public function category()
{
    return $this->hasMany(Category::class, 'id', 'category_id');
}

在控制器中

return Post::with('categories.category')->orderby('id','desc')->get();

我的结果是

 [
  {
    "id": 50,
    "categories": [
      {
        "id": 92,
        "category_id": 11,
        "category": [
          {
            "id": 11,
            "name": "JXrfLHdQVNON",
            "image": null
          }
        ]
      }
    ]
  }
]

我希望它像

[
  {
    "id": 50,
    "categories": [
      {
        "id": 1,
        "name": "category_name",
        "image": null
      }
    ]
  }
]

有办法吗? 我一直在玩这个,还没有设法找到一种简单的方法

在您的Post模型中:

 public function categories()
 {
        return $this->belongsToMany('App\Model\Category','post_categories','post_id','category_id')->withTimestamps();
 }

在您的控制器中:

return Post::with('categories:id,name,image')->orderBy('id','desc')->get();

这是多对多的关系。 确保您的关系建立正确。 如果要选择特定的列,可以执行以下操作:

return Post::with('categories.category:id,name')->orderby('id','desc')->get();

它将返回类别表/模型的列id, name 您必须指定id执行此操作。

https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

https://laravel.com/docs/5.7/eloquent-relationships#eager-loading

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM